我如何获得用户的IP地址?
InetAddress ip;
try {
ip = InetAddress.getLocalHost();
System.out.println("Current IP address : " + ip.getHostAddress());
} catch (UnknownHostException e) {
e.printStackTrace();
}
返回:127.0.0.1
我知道那不是我的IP.这是我的本地IP地址.如何使用java获取用户IP ..?
解决方法:
最短的方法是:
try {
InetAddress thisIp =InetAddress.getLocalHost();
System.out.println("IP:"+thisIp.getHostAddress());
}
catch(Exception e) {
e.printStackTrace();
}
但是getLocalHost文档说:
If there is a security manager, its checkConnect method is called with
the local host name and -1 as its arguments to see if the operation is
allowed. If the operation is not allowed, an InetAddress representing
the loopback address is returned.
在某些情况下,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 ifaces =
NetworkInterface.getNetworkInterfaces();
ifaces.hasMoreElements(); )
{
NetworkInterface iface = ifaces.nextElement();
System.out.println(iface.getName() + ":");
for (Enumeration 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();
}
参考文献:
标签:java,ip-address,ip
来源: https://codeday.me/bug/20190613/1232217.html