gpt4 book ai didi

Java获取本地IP

转载 作者:IT老高 更新时间:2023-10-28 20:39:38 25 4
gpt4 key购买 nike

我正在尝试获取本地 IP。它应该适用于

System.out.println(Inet4Address.getLocalHost().getHostAddress());

InetAddress addr = InetAddress.getLocalHost();
ip = addr.getHostAddress();
System.out.println("Ip: " + ip);

但它总是返回 192.168.178.154 而不是 192.168.178.119(这是我的真实本地 IP(终端 --> ifconfig) )

我该怎么办?

最佳答案

听起来你有两个 IP 地址。

On a computer that has one network adapter, the IP address that is chosen is the Primary IP address of the network adaptor in the computer. However, on a multiple-homed computer, the stack must first make a choice. The stack cannot make an intelligent choice until it knows the target IP address for the connection.

When the program sends a connect() call to a target IP address, or sends a send() call to a UDP datagram, the stack references the target IP address, and then examines the IP route table so that it can choose the best network adapter over which to send the packet. After this network adapter has been chosen, the stack reads the Primary IP address associated with that network adapter and uses that IP address as the source IP address for the outbound packets.

Document

如果您想激活第二个 IP 及其例如 LAN,请将其拔下并在 10 秒后重新插入。其他 IP 可能会被选为路由表中的主机 IP。

您可以从 getNetworkInterfaces 获取第二个 IP。

尝试运行以下代码:

public static void main(String[] args) throws Exception
{
System.out.println("Your Host addr: " + InetAddress.getLocalHost().getHostAddress()); // often returns "127.0.0.1"
Enumeration<NetworkInterface> n = NetworkInterface.getNetworkInterfaces();
for (; n.hasMoreElements();)
{
NetworkInterface e = n.nextElement();

Enumeration<InetAddress> a = e.getInetAddresses();
for (; a.hasMoreElements();)
{
InetAddress addr = a.nextElement();
System.out.println(" " + addr.getHostAddress());
}
}
}

关于Java获取本地IP,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19476872/

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