How to get the IP of this machine in the application development?
I am in the development of an online system when there is such a need, the method is very simple Ah, Google a bit, so the following code:
Programme one:
enumeration<networkinterface> interfaces =networkinterface.getnetworkinterfaces (); if(Interfaces! =NULL) { while(Interfaces.hasmoreelements ()) {Try{networkinterface Network=interfaces.nextelement (); if("Eth0". Equals (Network.getname ())) {//Verify that only eth0 will get IPEnumeration<inetaddress> addresses =network.getinetaddresses (); if(Addresses! =NULL) { while(Addresses.hasmoreelements ()) {Try{inetaddress Address=addresses.nextelement (); if(isvalidaddress (address)) {returnaddress; } } Catch(Throwable e) {if(logger.iswarnenabled ()) {Logger.warn ("[GetLocalAddress0] Failed to retriving IP address," +e.getmessage (), E); } } } } } } Catch(Throwable e) {if(logger.iswarnenabled ()) {Logger.warn ("[GetLocalAddress0] Failed to retriving IP address," +e.getmessage (), E); } } } }
Why do you add judgment eth0 to this piece of code? Because the general online server may not only have a network card, our online intranet is used eth0, so you can write dead. But it's not good after all. How to solve it?
Scenario Two:
A server IP is known on the line and can be connected. Get native intranet IP via socket link
1 Private Staticinetaddress getlocalhostbysocket (inetsocketaddress remoteaddress) {2InetAddress host =NULL;3 Try {4 //even remote address5Socket socket =NewSocket ();6 Try {7Socket.connect (remoteaddress, 1000);8 //get Local address9Host =socket.getlocaladdress ();Ten}finally { One Try { A socket.close (); -}Catch(Throwable e) { - } the } -}Catch(Exception e) { -Logger.warn ("Can not connect to host {}, cause by: {}", - remoteaddress.tostring (), E.getmessage ()); + } - returnHost;}
Java Apps get native IP