I have an application in Java which needs the IP address of particular machine in order to communicate in Ubuntu. I tried using the Jjava function InetAddress.getLocalHost().getHostAddress()
to fetch the IP address of the desired machine but it returns the loop back address that is 127.0.0.1. The external IP address of my system is 192.168.1.1.
Is there any function using which I can retrieve only the latter one?
Asked
Active
Viewed 77 times
0

Cœur
- 37,241
- 25
- 195
- 267

Dila Gurung
- 1,726
- 21
- 26
-
Why? Why do you think you need the IP address of your own machine? Do you mean you need to get the IP address of *another* machine? If so, `getLocalHost()` is hardly the way to proceed. – user207421 Apr 17 '15 at 04:51
-
Have you googled about this yet? Besides this maybe already answered in this community, please refer to: http://stackoverflow.com/questions/2381316/java-inetaddress-getlocalhost-returns-127-0-0-1-how-to-get-real-ip – Nirmal Apr 17 '15 at 04:55
-
1i got a solutionimport java.net.InetAddress; import java.net.*; import java.util.*; class IPAddress { public static void main(String args[]) throws Exception { int i=0; Enumeration en = NetworkInterface.getNetworkInterfaces(); while(en.hasMoreElements()){ //System.out.println(i); NetworkInterface ni=(NetworkInterface) en.nextElement(); Enumeration ee = ni.getInetAddresses(); int j=0; while(ee.hasMoreElements()) { InetAddress ia= (InetAddress) ee.nextElement(); if(i==0 && j==1) { System.out.println(ia.getHostAddress()); } j++;} i++; } } } – Dila Gurung Apr 17 '15 at 05:04
-
Don't post code in comments. It's a waste of time. You can see for yourself that it is completely and utterly illegible. Edit it into your question. And speaking of questions, you haven't answered any of mine. – user207421 Apr 17 '15 at 05:46
1 Answers
-2
/**
The following code solved my problem
**/
import java.net.InetAddress;
import java.net.*;
import java.util.*;
class IPAddress
{
public static void main(String args[]) throws Exception
{
int i=0;
Enumeration en = NetworkInterface.getNetworkInterfaces();
while(en.hasMoreElements()){
//System.out.println(i);
NetworkInterface ni=(NetworkInterface) en.nextElement();
Enumeration ee = ni.getInetAddresses();
int j=0;
while(ee.hasMoreElements()) {
InetAddress ia= (InetAddress) ee.nextElement();
if(i==0 && j==1)
{ System.out.println(ia.getHostAddress());
}
j++;}
i++;
}
}
}

Dila Gurung
- 1,726
- 21
- 26
-
Only for one specific configuration where the IP address you need is the 2nd IP address of the first NIC. That could change overnight on this host, and be completely different in another host. It isn't a viable solution. – user207421 Apr 17 '15 at 05:48
-
2Mr EJP ....telll me the viable solution..as i need to implement it in different host having different network interfaces – Dila Gurung Apr 17 '15 at 06:44
-
*You* tell *me* the answer to *my* question. *Why* do you need the local address of your machine? – user207421 Apr 17 '15 at 06:56