4 java ip ip-address
我如何获得用户的IP地址?
InetAddress ip;
try {
ip = InetAddress.getLocalHost();
System.out.println("Current IP address : " + ip.getHostAddress());
} catch (UnknownHostException e) {
e.printStackTrace();
}
Run Code Online (Sandbox Code Playgroud)
返回:127.0.0.1
我知道那不是我的IP.这是我的本地IP地址.如何使用java获取用户IP ..?
最短的方法是:
try {
InetAddress thisIp =InetAddress.getLocalHost();
System.out.println("IP:"+thisIp.getHostAddress());
}
catch(Exception e) {
e.printStackTrace();
}
Run Code Online (Sandbox Code Playgroud)
然而, getLocalHost文档说:
如果有安全管理器,则使用本地主机名调用其checkConnect方法,并将-1作为其参数,以查看是否允许该操作.如果不允许该操作,则返回表示环回地址的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);
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
或者:
尝试使用此功能(首先输出应该是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();
}
Run Code Online (Sandbox Code Playgroud)
参考文献:
| 归档时间: |
|
| 查看次数: |
1086 次 |
| 最近记录: |