Talk more about Java get the native IP address

Source: Internet
Author: User
Tags stub

First of all, if you search for "java get native IP address", basically the data found is Useless.
For example this article: http://www.cnblogs.com/zrui-xyu/p/5039551.html
The actual code is not allowed in a complex environment.


One of the more popular sayings on the web is inetaddress.getlocalhost (). gethostaddress ()
Seems simple, but ignores the problem that the IP address in the current network environment more complex, such as lan,wifi, Bluetooth hotspot, virtual Machine network card ...
That is, there are many network interfaces (networks interfaces), Each network interface contains an IP address, not all IP addresses can be accessed by external or local area network, such as virtual machine card address and so On.
That is to say Inetaddress.getlocalhost (). gethostaddress () IP is not necessarily the correct ip.

Before writing the code, clarify some rules:

    • 127.xxx.xxx.xxx belongs to the "loopback" address, that is, only your own native visible, is the local address, more common has 127.0.0.1;
    • The 192.168.xxx.xxx belongs to the private privately owned address (site address), which is internal to the local organization and can only be seen on local lans. The same 10.xxx.xxx.xxx, from 172.16.xxx.xxx to 172.31.xxx.xxx are private addresses, but also belong to the organization internal access;
    • 169.254.xxx.xxx belongs to the connection local address (link locally IP) and is available in a separate network segment
    • From 224.xxx.xxx.xxx to 239.xxx.xxx.xxx belong to the multicast address
    • The more special 255.255.255.255 belong to the broadcast Address.
    • In addition, the address is a point-to-point available public IPv4 address

Get the correct posture for the native IP address:

 packageiptest;Importjava.net.Inet4Address;Importjava.net.InetAddress;Importjava.net.NetworkInterface;Importjava.net.SocketException;Importjava.net.UnknownHostException;Importjava.util.Enumeration; public classTest { publicTest () {//TODO auto-generated Constructor stub    }     public Static voidmain (string[] Args) {//TODO auto-generated Method Stubinetaddress ip; Try {            //This kind of IP is easy to get wrong//System.out.println ("current IP address:" +//inetaddress.getlocalhost (). gethostaddress ()); //not necessarily accurate Ip-fetch method//for example, this article:http://www.cnblogs.com/zrui-xyu/p/5039551.htmlSystem.out.println ("get LocalHost Address:" +getlocalhostaddress (). gethostaddress ()); //correct IP Pick-up methodSystem.out.println ("get LocalHost LAN Address:" +getlocalhostlanaddress (). gethostaddress ()); } Catch(unknownhostexception E) {e.printstacktrace (); }    }    //correct IP law, that is, priority to take site-local address    Private StaticInetAddress getlocalhostlanaddress ()throwsunknownhostexception {Try{inetaddress candidateaddress=NULL; //Traverse all the network interfaces             for(enumeration ifaces =networkinterface.getnetworkinterfaces (); ifaces.hasmoreelements ();) {networkinterface Iface=(networkinterface) ifaces.nextelement (); //traverse IP on all interfaces                 for(enumeration Inetaddrs =iface.getinetaddresses (); inetaddrs.hasmoreelements ();) {inetaddress InetAddr=(inetaddress) inetaddrs.nextelement (); if(!inetaddr.isloopbackaddress ()) {//exclude loopback type address                        if(inetaddr.issitelocaladdress ()) {//if It's a site-local address, that's it.                            returninetaddr; } Else if(candidateaddress = =NULL) {                            //site-local type of Address not found, first record candidate addressCandidateaddress =inetaddr; }                    }                }            }            if(candidateaddress! =NULL) {                returncandidateaddress; }            //If the Non-loopback address is not found. use only the most selected scenarioInetAddress jdksuppliedaddress =Inetaddress.getlocalhost (); if(jdksuppliedaddress = =NULL) {                Throw NewUnknownhostexception ("the JDK Inetaddress.getlocalhost () method unexpectedly returned Null.")); }            returnjdksuppliedaddress; } Catch(Exception e) {unknownhostexception unknownhostexception=NewUnknownhostexception ("Failed to determine LAN address:" +e);            Unknownhostexception.initcause (e); Throwunknownhostexception; }    }    //from this article:http://www.cnblogs.com/zrui-xyu/p/5039551.html    //the actual code is not Allowed.    Private StaticInetAddress getlocalhostaddress ()throwsunknownhostexception {enumeration allnetinterfaces; Try{allnetinterfaces=networkinterface.getnetworkinterfaces (); InetAddress IP=NULL;  while(allnetinterfaces.hasmoreelements ()) {networkinterface netinterface=(networkinterface) allnetinterfaces.nextelement (); Enumeration addresses=netinterface.getinetaddresses ();  while(addresses.hasmoreelements ()) {ip=(inetaddress) addresses.nextelement (); if(!ip.issitelocaladdress () &&!ip.isloopbackaddress () && ip.gethostaddress (). indexOf (":") = =-1) {                        if(ip! =NULL&& IPinstanceofInet4address) {                            returnip; }                    }                }            }        } Catch(socketexception E) {//TODO auto-generated Catch blockE.printstacktrace (); } inetaddress jdksuppliedaddress=Inetaddress.getlocalhost (); if(jdksuppliedaddress = =NULL) {            Throw NewUnknownhostexception ("the JDK Inetaddress.getlocalhost () method unexpectedly returned Null.")); }        returnjdksuppliedaddress; }}

Talk more about Java get the native IP address

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.