gpt4 book ai didi

java - Java 的 IP 地址

转载 作者:搜寻专家 更新时间:2023-11-01 01:55:08 25 4
gpt4 key购买 nike

我如何获得用户的 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() 不会查询您的接口(interface),它只是返回常量 127.0.0.1(对于 IPv4))

我认为 NetworkInterface.getNetworkInterfaces 是您枚举所有可能性所需要的。这是一个不显示虚拟地址但适用于“主”接口(interface)的示例:

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();
}

引用资料:

关于java - Java 的 IP 地址,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11941059/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com