Monday, September 17, 2007

Determine Local IP Addresses

Here's a quick how-to for determining the IP Addresses your local machine has.

NOTE: This version (i've edited the post a couple of times now), will return all IPs associated with any network interface on the machine. Also, it's been tested on Windows and several flavors of linux.



public ArrayList getIPs() throws SocketException {
ArrayList ips = new ArrayList();
Enumeration m = NetworkInterface.getNetworkInterfaces();
while(m.hasMoreElements()) {
NetworkInterface ni = m.nextElement();
Enumeration addresses = ni.getInetAddresses();
while (addresses.hasMoreElements()) {
InetAddress address = addresses.nextElement();
String ip = address.getHostAddress();

// filter out Inet6 Addr Entries
if (ip.indexOf(":") == -1) {
ips.add(ip);
}
}
}

return ips;
}

No comments: