PackageHope.ipaddress.demo;Importjava.net.InetAddress;ImportJava.net.NetworkInterface;Importjava.net.SocketException;Importjava.util.Enumeration;/*** Get current server IP *@authorHP **/ Public classIpdemo {/** * @paramargs*/ Public Static voidMain (string[] args) {System.out.println (Getmyip ()); } @SuppressWarnings ("Rawtypes") Public Staticstring Getmyip () {string Localip=NULL;//local IP, which is returned if no extranet IP is configuredString Netip =NULL;//External Network IP Try{Enumeration Netinterfaces=networkinterface.getnetworkinterfaces (); InetAddress IP=NULL; Booleanfinded =false;//whether to find an extranet IP while(Netinterfaces.hasmoreelements () &&!finded) {networkinterface ni=(NetworkInterface) netinterfaces.nextelement (); Enumeration Address=ni.getinetaddresses (); while(Address.hasmoreelements ()) {IP=(inetaddress) address.nextelement (); if(!ip.issitelocaladdress () &&!ip.isloopbackaddress () && ip.gethostaddress (). IndexOf (":") = =-1) {//External Network IPNetip =ip.gethostaddress (); finded=true; Break; } Else if(Ip.issitelocaladdress () &&!ip.isloopbackaddress () && ip.gethostaddress (). IndexOf (":") = =-1) {//Intranet IPLocalip =ip.gethostaddress (); } } } } Catch(SocketException e) {e.printstacktrace (); } if(Netip! =NULL&& "". Equals (Netip)) { returnNetip; } Else { returnLocalip; } }}
Java gets the current server IP implementation