我有一个 Java 应用程序,它需要特定机器的 IP 地址才能在 Ubuntu 中进行通信。我尝试使用 Jjava 函数InetAddress.getLocalHost().getHostAddress()
来获取所需机器的 IP 地址,但它返回的环回地址为 127.0.0.1。我系统的外部 IP 地址是 192.168.1.1。有什么功能可以让我只检索后一个功能吗?
问问题
62 次
1 回答
-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++;
}
}
}
于 2015-04-17T05:06:32.300 回答