public
Created

Accepted answer for http://stackoverflow.com/questions/494465/how-to-enumerate-ip-addresses-of-all-enabled-nic-cards-from-java?lq=1 with imports and all the log statements replaced with System.out.println() calls. To run, paste the code into a file called ShowIPs.java, and either: - Place the file in a package called "run" and run main - Remove the package declaration and run the code in something like http://ideone.com/

  • Download Gist
ShowIPs.java
Java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
package run;
 
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.Enumeration;
 
public class ShowIPs {
 
public static void main(String[] args) {
try {
InetAddress localhost = InetAddress.getLocalHost();
System.out.println(" IP Addr: " + localhost.getHostAddress());
// Just in case this host has multiple IP addresses....
InetAddress[] allMyIps = InetAddress.getAllByName(localhost.getCanonicalHostName());
if (allMyIps != null && allMyIps.length > 1) {
System.out.println(" Full list of IP addresses:");
for (int i = 0; i < allMyIps.length; i++) {
System.out.println(" " + allMyIps[i]);
}
}
} catch (UnknownHostException e) {
System.out.println(" (error retrieving server host name)");
}
 
try {
System.out.println("Full list of Network Interfaces:");
for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) {
NetworkInterface intf = en.nextElement();
System.out.println(" " + intf.getName() + " " + intf.getDisplayName());
for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements(); ) {
System.out.println(" " + enumIpAddr.nextElement().toString());
}
}
} catch (SocketException e) {
System.out.println(" (error retrieving network interface list)");
}
}
 
}

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.