此代码用于将本地IP地址返回为192.xxx.x.xxx,但现在返回127.0.0.1.请帮助我为什么相同的代码返回不同的值.我需要在linux OS上观看一些东西.
import java.util.*;
import java.lang.*;
import java.net.*;
public class GetOwnIP
{
public static void main(String args[]) {
try{
InetAddress ownIP=InetAddress.getLocalHost();
System.out.println("IP of my system is := "+ownIP.getHostAddress());
}catch (Exception e){
System.out.println("Exception caught ="+e.getMessage());
}
}
}
Run Code Online (Sandbox Code Playgroud)
Jon*_*eet 30
127.0.0.1是环回适配器 - 它是对(有点故障)问题"我的IP地址是什么?"的完全正确的回应.
问题是该问题有多个正确的答案.
编辑:文档getLocalHost
说:
如果有安全管理器,则使用本地主机名调用其checkConnect方法,并将-1作为其参数,以查看是否允许该操作.如果不允许该操作,则返回表示环回地址的InetAddress.
行为的变化是否可能是由权限的变化引起的?
编辑:我相信这NetworkInterface.getNetworkInterfaces
就是你需要列举的所有可能性.这是一个不显示虚拟地址的示例,但适用于"主要"接口:
import java.net.*;
import java.util.*;
public class Test
{
public static void main(String[] args)
throws Exception // Just for simplicity
{
for (Enumeration<NetworkInterface> ifaces =
NetworkInterface.getNetworkInterfaces();
ifaces.hasMoreElements(); )
{
NetworkInterface iface = ifaces.nextElement();
System.out.println(iface.getName() + ":");
for (Enumeration<InetAddress> addresses =
iface.getInetAddresses();
addresses.hasMoreElements(); )
{
InetAddress address = addresses.nextElement();
System.out.println(" " + address);
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
(我忘记Enumeration<T>
了直接使用这种类型有多糟糕!)
以下是我的笔记本电脑上的结果:
lo:
/127.0.0.1
eth0:
/169.254.148.66
eth1:
eth2:
ppp0:
/10.54.251.111
Run Code Online (Sandbox Code Playgroud)
(我不认为这会泄露任何非常敏感的信息:)
如果您知道要使用哪个网络接口,请调用NetworkInterface.getByName(...)
然后查看该接口的地址(如上面的代码所示).
当您使用InetAddress.getLocalHost()时,您无法保证获得特定的接口,即.你可以收到环回(127)接口或连接的接口.
为了确保始终获得外部接口,您应该使用java.net.NetworkInterface类.静态getByName(String)类将为您提供具有已定义名称的接口(例如"eth0").然后,您可以使用getInetAddresses()函数来获取绑定到该接口的IP地址(可能只是一个).
NetworkInterface ni = NetworkInterface.getByName("eth1");
ni.getInetAddresses();
Run Code Online (Sandbox Code Playgroud)