The below Java code, myIP.java, list my IP address.
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;
class myIP {
public static void main(String[] args) {
System.out.println(getIpAddress());
}
private static String getIpAddress(){
String ip = "";
try {
Enumeration<NetworkInterface> enumNetworkInterfaces =
NetworkInterface.getNetworkInterfaces();
while(enumNetworkInterfaces.hasMoreElements()){
NetworkInterface networkInterface =
enumNetworkInterfaces.nextElement();
Enumeration<InetAddress> enumInetAddress =
networkInterface.getInetAddresses();
while(enumInetAddress.hasMoreElements()){
InetAddress inetAddress = enumInetAddress.nextElement();
String ipAddress = "";
if(inetAddress.isLoopbackAddress()){
ipAddress = "LoopbackAddress: ";
}else if(inetAddress.isSiteLocalAddress()){
ipAddress = "SiteLocalAddress: ";
}else if(inetAddress.isLinkLocalAddress()){
ipAddress = "LinkLocalAddress: ";
}else if(inetAddress.isMulticastAddress()){
ipAddress = "MulticastAddress: ";
}
ip += ipAddress + inetAddress.getHostAddress() + "\n";
}
}
} catch (SocketException e) {
ip += "Something Wrong! " + e.toString() + "\n";
}
return ip;
}
}
|
Get my IP Address using Java |
No comments:
Post a Comment