最短的方法是:
try {
InetAddress thisIp =InetAddress.getLocalHost();
System.out.println("IP:"+thisIp.getHostAddress());
}
catch(Exception e) {
e.printStackTrace();
}
但是 getLocalHost
文档说:
如果有安全管理器,则使用本地主机名和 -1 作为其参数调用其 checkConnect 方法,以查看是否允许该操作。如果不允许该操作,则返回表示环回地址的 InetAddress。
并且在某些情况下InetAddress.getLocalHost()
不咨询您的接口,它只是返回常量 127.0.0.1(对于 IPv4))
我认为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);
}
}
}
}
或者:
尝试使用这个(第一个输出应该是 PC 名称后的 IP):
InetAddress[] localaddr;
String computername = null;
try {
computername = InetAddress.getLocalHost().getHostName();//get pc name
} catch (UnknownHostException ex) {
ex.printStackTrace();
}
System.out.println(computername);
try {
localaddr = InetAddress.getAllByName(computername);
for (int i = 0; i < localaddr.length; i++) {
System.out.println("\n" + localaddr[i].getHostAddress());
}
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
参考资料: