Get IP Address
The Java code is as follows:
Import java.net.Inet4Address;
Import java.net.InetAddress;
Import Java.net.NetworkInterface;
Import java.net.SocketException;
Import java.net.UnknownHostException;
Import java.util.Enumeration;
public class Testgetip {public static void main (string[] args) {Testgetip testgetip = new Testgetip ();
Testgetip.printaddresses ();
System.out.println ("\n\n\n\n");
System.out.println (Testgetip.getip ()); //Find a reasonable IPv4 public String GetIP () {try {//hostname to find IP inetaddress addres
s = inetaddress.getlocalhost (); if (address.isloopbackaddress ()) {enumeration<networkinterface> allnetinterfaces = NetworkInterface
. Getnetworkinterfaces (); while (Allnetinterfaces.hasmoreelements ()) {NetworkInterface netinterface = (networkinterface) allNet
Interfaces.nextelement (); enumeration<inetaddress> addresses = netinterface.gEtinetaddresses ();
while (Addresses.hasmoreelements ()) {inetaddress IP = addresses.nextelement ();
if (!ip.islinklocaladdress () &&!ip.isloopbackaddress () && IP instanceof inet4address) {
return ip.gethostaddress ();
}}} return Address.gethostaddress ();
catch (Unknownhostexception e) {e.printstacktrace ();
return null;
catch (SocketException e) {e.printstacktrace ();
return null; ///All network interfaces public void Printaddresses () {try {Enumeration<networkinterface> ;
Allnetinterfaces = Networkinterface.getnetworkinterfaces (); while (Allnetinterfaces.hasmoreelements ()) {NetworkInterface netinterface = (networkinterface) allNetIn Terfaces.nextelement ();
Remove loopback interface, Sub-interface, not running and interface if (Netinterface.isloopback () | | netinterface.isvirtual () | |!netinterface.isup ()) {
Continue
} enumeration<inetaddress> addresses = Netinterface.getinetaddresses ();
while (Addresses.hasmoreelements ()) {inetaddress IP = addresses.nextelement ();
if (IP!= null) {System.out.println ("IP =" + ip.gethostaddress ()); IPv4 if (IP instanceof inet4address) {System.out.println ("IPv4 ="
+ ip.gethostaddress ()); if (Ip.gethostaddress () startswith ("the") | | ip.gethostaddress () startswith ("10") | | Ip.gethostaddress (). StartsWith ("172") | |
Ip.gethostaddress (). StartsWith ("169")) {//Intranet} catch (SocketException e) {
System.err.println ("Error when getting host IP address" + e.getmessage ());
}
}
}