Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java InetAddress.getLocalHost(); returns 127.0.0.1 ... how to get REAL IP?

I'm writing a simple networking app. I need to know the real IP of my machine on the network, like 192.168.1.3 . getLocalHost returns 127.0.0.1 (on Linux, I don't know if it is the same on windows). How to do it?

like image 605
gotch4 Avatar asked Mar 04 '10 17:03

gotch4


2 Answers

If you actually want to work with all of the IP addresses on the machine you can get those with the NetworkInterface class. Of course, then you need to which one you actually want to use, but that's going to be different depending on what you're using it for, or you might need to expand the way you're using it to account for multiple addresses.

import java.net.*; import java.util.*;  public class ShowInterfaces {         public static void main(String[] args) throws Exception         {                 System.out.println("Host addr: " + InetAddress.getLocalHost().getHostAddress());  // often returns "127.0.0.1"                 Enumeration<NetworkInterface> n = NetworkInterface.getNetworkInterfaces();                 for (; n.hasMoreElements();)                 {                         NetworkInterface e = n.nextElement();                         System.out.println("Interface: " + e.getName());                         Enumeration<InetAddress> a = e.getInetAddresses();                         for (; a.hasMoreElements();)                         {                                 InetAddress addr = a.nextElement();                                 System.out.println("  " + addr.getHostAddress());                         }                 }         } } 
like image 70
Eric Avatar answered Sep 22 '22 19:09

Eric


As the machine might have multiple addresses, it's hard to determine which one is the one for you. Normally, you want the system to assign an IP based on its routing table. As the result depends on the IP you'd like to connect to, there is a simple trick: Simply create a connection and see what address you've got from the OS:

// output on my machine: "192.168.1.102" Socket s = new Socket("192.168.1.1", 80); System.out.println(s.getLocalAddress().getHostAddress()); s.close();  // output on my machine: "127.0.1.1" System.out.println(InetAddress.getLocalHost().getHostAddress()); 

I'm not sure whether it's possible to do this without establishing a connection though. I think I've once managed to do it with Perl (or C?), but don't ask me about Java. I think it might be possible to create a UDP socket (DatagramSocket) without actually connecting it.

If there is a NAT router on the way you won't be able to get the IP that remote hosts will see though. However, as you gave 192.* as an example, I think you don't care.

like image 44
sfussenegger Avatar answered Sep 22 '22 19:09

sfussenegger