Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java getting my IP address

Tags:

java

wifi

ip

I am trying to get my Internet IP address in Java but I keep getting my local address (ie: 127.0.0.1), when my IP address is 192.168.0.xxx

I am using the line:

InetAddress.getLocalHost().getHostAddress(); 

which seems standard to get the IP address, but it is not what I am looking for. Every tutorial says to use this line, so I am a little confused.

Could anyone please let me know how I can get my correct IP address please?


I'm running on a device that is connected to WiFi, and I'm not using any cable. I am connecting to a server using the IP given by ifconfig inet addr, and I am looking to get the device's inet addr. I could check the IP of the socket on the server side, but thought it'd be nicer if the device (client) tells the server which IP he is expecting other devices to connect on.

like image 853
Jary Avatar asked Nov 10 '11 17:11

Jary


People also ask

How do I find the IP address and machine address of the Java network package program?

InetAddress. getLocalHost() is used to find the private IP addresses used in LAN or any other local network. To find public IP, we use http://bot.whatismyipaddress.com (An online utility to find your public IP), we open the URL, read a line and print the line. Below is the Java implementation of the above steps.

Which function is used to get the current machine's IP address?

getLocalHost() should give you the IP address of this host.


1 Answers

    String ip;     try {         Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();         while (interfaces.hasMoreElements()) {             NetworkInterface iface = interfaces.nextElement();             // filters out 127.0.0.1 and inactive interfaces             if (iface.isLoopback() || !iface.isUp())                 continue;              Enumeration<InetAddress> addresses = iface.getInetAddresses();             while(addresses.hasMoreElements()) {                 InetAddress addr = addresses.nextElement();                 ip = addr.getHostAddress();                 System.out.println(iface.getDisplayName() + " " + ip);             }         }     } catch (SocketException e) {         throw new RuntimeException(e);     } 
like image 109
roylaurie Avatar answered Sep 30 '22 09:09

roylaurie