简体   繁体   中英

Unable to fetch IP Address of machine

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?

/**

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++;
 }

   }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM