我有一个Java应用程序需要特定机器的IP地址才能在Ubuntu中进行通信。我尝试使用Jjava函数InetAddress.getLocalHost().getHostAddress()
来获取所需机器的IP地址,但它返回的循环地址为127.0.0.1。我系统的外部IP地址是192.168.1.1。
是否有任何功能我只能检索后者?
答案 0 :(得分:-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++;
}
}
}