Snippet: NETSTAT in Java with command line call
import java.io.IOException;
import java.util.*;
import java.util.regex.Pattern;
public class Netstat
{
public static class Protocoll
{
public String protocoll;
public String localAddress;
public String remoteAddress;
public String status;
public Protocoll( String protocoll, String localAddress, String remoteAddress, String status )
{
this.protocoll = protocoll;
this.localAddress = localAddress;
this.remoteAddress = remoteAddress;
this.status = status;
}
@Override
public String toString()
{
return String.format( "%-6s %-22s %-22s %s", protocoll, localAddress, remoteAddress, status );
}
}
public static void main( String[] args ) throws IOException
{
for ( Protocoll p : netStat() )
System.out.println( p );
}
public static Iterable netStat() throws IOException
{
Collection result = new ArrayList();
ProcessBuilder builder = new ProcessBuilder( "netstat", "-n" );
Process p = builder.start();
try ( Scanner scanner = new Scanner( p.getInputStream() ) ) {
Pattern pattern = Pattern.compile( "(TCP|UDP)\\s+(\\S+)\\s+(\\S+)\\s+(\\S+)" );
while ( scanner.findWithinHorizon( pattern, 0 ) != null )
result.add( new Protocoll( scanner.match().group( 1 ), scanner.match().group( 2 ), scanner.match().group( 3 ), scanner.match().group( 4 ) ) );
}
return result;
}
}
This leads to something like
TCP 127.0.0.1:16709 127.0.0.1:49159 HERGESTELLT
TCP 127.0.0.1:19872 127.0.0.1:49176 HERGESTELLT
TCP 127.0.0.1:49159 127.0.0.1:16709 HERGESTELLT
TCP 127.0.0.1:49176 127.0.0.1:19872 HERGESTELLT
TCP 127.0.0.1:49189 127.0.0.1:49190 HERGESTELLT
TCP 127.0.0.1:49190 127.0.0.1:49189 HERGESTELLT
2 Kommentare
Thomas Wenzlaff ·
Hallo, da muss für Mac OS wohl der regex angepasst werden, sonst läuft da nichts. Hier mal eine netstat -n Ausgabe aus dem Terminal: Active Internet connections Proto Recv-Q Send-Q Local Address Foreign Address (state) tcp4 0 0 192.xxx.x.xxx.xxxxx 173.xxx.xx.xx.80 ESTABLISHED Liebe Grüße Thomas
privacy ·
Sorry es muss mal erwähnt werden da es nicht das erste mal hier ist: Sie verwenden die Process Klasse falsch. getInputStream und getErrorStream müssen async. gelesen werden und waitFor aufgerufen oder exitValue gepollt werden. Alles andere ist falsch und kann je nach Timing/Pipebuffergrössen zu Deadlocks führen..
Die bisherigen Kommentare wurden aus WordPress übernommen. Neue Kommentare sind derzeit geschlossen.