Java获得本地IP [英] Java get local IP

查看:262
本文介绍了Java获得本地IP的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图获取本地IP。它应该与

Im trying to get the local IP. It should work with

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 ))

but it always returns 192.168.178.154 instead of 192.168.178.119(This is my real local IP(Terminal --> ifconfig))

我该怎么办?

推荐答案

听起来你有两个IP地址。

Sounds like you have two IP addresses.


在具有一个网络适配器的计算机上,所选的IP地址是计算机中网络适配器的主IP地址。但是,在多宿主计算机上,堆栈必须首先进行选择。在知道连接的目标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.

当程序向目标IP地址发送connect()调用或发送时对UDP数据报的send()调用,栈引用目标IP地址,然后检查IP路由表,以便它可以选择最佳的网络适配器来发送数据包。选择此网络适配器后,堆栈将读取与该网络适配器关联的主IP地址,并使用该IP地址作为出站数据包的源IP地址。

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.

文档

如果要激活第二个IP及其例如LAN,请拔掉它以及之后10秒插回。可以在路由表中选择其他IP作为主机IP。

If you want to activate second IP and its for example LAN, unplug it and after 10 sec plug in back. Other IP might be selected as host IP in routing table.

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

You can get 2nd IP from getNetworkInterfaces.

尝试运行以下代码:

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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆