support -n flag and ip->hostname conversion

This commit is contained in:
Doug MacEachern 2005-03-11 01:27:19 +00:00
parent 757892710a
commit 7c901c486e
1 changed files with 37 additions and 4 deletions

View File

@ -1,5 +1,8 @@
package net.hyperic.sigar.cmd; package net.hyperic.sigar.cmd;
import java.net.InetAddress;
import java.net.UnknownHostException;
import net.hyperic.sigar.SigarException; import net.hyperic.sigar.SigarException;
import net.hyperic.sigar.NetConnection; import net.hyperic.sigar.NetConnection;
import net.hyperic.sigar.NetFlags; import net.hyperic.sigar.NetFlags;
@ -9,6 +12,8 @@ import net.hyperic.sigar.NetFlags;
*/ */
public class Netstat extends SigarCommandBase { public class Netstat extends SigarCommandBase {
private static boolean isNumeric;
public Netstat(Shell shell) { public Netstat(Shell shell) {
super(shell); super(shell);
} }
@ -28,6 +33,7 @@ public class Netstat extends SigarCommandBase {
//poor mans getopt. //poor mans getopt.
public static int getFlags(String[] args, int flags) { public static int getFlags(String[] args, int flags) {
int proto_flags = 0; int proto_flags = 0;
isNumeric = false;
for (int i=0; i<args.length; i++) { for (int i=0; i<args.length; i++) {
String arg = args[i]; String arg = args[i];
@ -44,6 +50,9 @@ public class Netstat extends SigarCommandBase {
case 'a': case 'a':
flags |= NetFlags.CONN_SERVER | NetFlags.CONN_CLIENT; flags |= NetFlags.CONN_SERVER | NetFlags.CONN_CLIENT;
break; break;
case 'n':
isNumeric = true;
break;
case 't': case 't':
proto_flags |= NetFlags.CONN_TCP; proto_flags |= NetFlags.CONN_TCP;
break; break;
@ -70,6 +79,30 @@ public class Netstat extends SigarCommandBase {
return flags; return flags;
} }
private String formatPort(long port) {
if (port == 0) {
return "*";
}
return String.valueOf(port);
}
private String formatAddress(String address) {
if (isNumeric) {
return address;
}
if (address.equals("0.0.0.0")) {
return "*";
}
//advantage of InetAddress' lookup cache.
try {
InetAddress addr = InetAddress.getByName(address);
return addr.getHostName();
} catch (UnknownHostException e) {
return address;
}
}
//XXX currently weak sauce. should end up like netstat command. //XXX currently weak sauce. should end up like netstat command.
public void output(String[] args) throws SigarException { public void output(String[] args) throws SigarException {
//default //default
@ -87,11 +120,11 @@ public class Netstat extends SigarCommandBase {
println(conn.getTypeString() + println(conn.getTypeString() +
"\t" + "\t" +
conn.getLocalAddress() + ":" + formatAddress(conn.getLocalAddress()) + ":" +
conn.getLocalPort() + formatPort(conn.getLocalPort()) +
"\t" + "\t" +
conn.getRemoteAddress() + ":" + formatAddress(conn.getRemoteAddress()) + ":" +
conn.getRemotePort()); formatPort(conn.getRemotePort()));
} }
} }