无需连接到互联网即可获取本地IP地址

Luk*_*uth 34 java ip networking

所以,我正在尝试在我的本地网络中获取我的机器的IP地址(应该是这样192.168.178.41).

我的第一个意图是使用这样的东西:

InetAddress.getLocalHost().getHostAddress();
Run Code Online (Sandbox Code Playgroud)

但它只会返回127.0.0.1,这是正确的,但对我没有多大帮助.

我四处搜索并找到了这个答案/sf/answers/166697891/,它只是创建了Socket一些网页连接(例如"google.com")并从套接字获取本地主机地址:

Socket s = new Socket("google.com", 80);
System.out.println(s.getLocalAddress().getHostAddress());
s.close();
Run Code Online (Sandbox Code Playgroud)

这适用于我的机器(它返回192.168.178.41),但它需要连接到互联网才能工作.由于我的应用程序不需要互联网连接,并且每次启动应用程序尝试连接到Google时可能看起来"可疑",我不喜欢使用它的想法.

所以,经过一些更多的研究后,我偶然发现了NetworkInterface-class,其中(有一些工作)也会返回所需的IP地址:

Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
while (interfaces.hasMoreElements()){
    NetworkInterface current = interfaces.nextElement();
    System.out.println(current);
    if (!current.isUp() || current.isLoopback() || current.isVirtual()) continue;
    Enumeration<InetAddress> addresses = current.getInetAddresses();
    while (addresses.hasMoreElements()){
        InetAddress current_addr = addresses.nextElement();
        if (current_addr.isLoopbackAddress()) continue;
        System.out.println(current_addr.getHostAddress());
    }
}
Run Code Online (Sandbox Code Playgroud)

在我的机器上,这将返回以下内容:

name:eth1 (eth1)
fe80:0:0:0:226:4aff:fe0d:592e%3
192.168.178.41
name:lo (lo)
Run Code Online (Sandbox Code Playgroud)

它找到我的网络接口并返回所需的IP,但我不确定其他地址(fe80:0:0:0:226:4aff:fe0d:592e%3)的含义.

此外,我还没有找到一种方法从返回的地址(通过使用isXX()-object的-methods InetAddress)过滤它,然后使用RegEx,我觉得非常"脏".

除了使用RegEx或互联网之外的任何其他想法?

yan*_*kee 24

fe80:0:0:0:226:4aff:fe0d:592e是你的ipv6地址;-).

检查一下

if (current_addr instanceof Inet4Address)
  System.out.println(current_addr.getHostAddress());
else if (current_addr instanceof Inet6Address)
  System.out.println(current_addr.getHostAddress());
Run Code Online (Sandbox Code Playgroud)

如果您只关心IPv4,那么只需丢弃IPv6案例.但要注意,IPv6是未来的^^.

PS:检查你break的某些东西应该是continues.

  • @skaffmann:是的,在这个例子中,if是没有意义的,但是为了解释如何区分IPv4和IPv6,我不打算改变它.毕竟问题似乎也只是提取IPv4地址 (2认同)

tsd*_*sds 13

这也是一种java 8方式:

public static String getIp() throws SocketException {

    return Collections.list(NetworkInterface.getNetworkInterfaces()).stream()
            .flatMap(i -> Collections.list(i.getInetAddresses()).stream())
            .filter(ip -> ip instanceof Inet4Address && ip.isSiteLocalAddress())
            .findFirst().orElseThrow(RuntimeException::new)
            .getHostAddress();
}
Run Code Online (Sandbox Code Playgroud)


Ehu*_*Lev 8

public static String getIp(){
    String ipAddress = null;
    Enumeration<NetworkInterface> net = null;
    try {
        net = NetworkInterface.getNetworkInterfaces();
    } catch (SocketException e) {
        throw new RuntimeException(e);
    }

    while(net.hasMoreElements()){
        NetworkInterface element = net.nextElement();
        Enumeration<InetAddress> addresses = element.getInetAddresses();
        while (addresses.hasMoreElements()){
            InetAddress ip = addresses.nextElement();
            if (ip instanceof Inet4Address){

                if (ip.isSiteLocalAddress()){

                    ipAddress = ip.getHostAddress();
                }

            }

        }
    }
    return ipAddress;
}
Run Code Online (Sandbox Code Playgroud)


Ash*_*nto 5

import java.net.*;

public class Get_IP
{
    public static void main(String args[])
    {
        try
        {
            InetAddress addr = InetAddress.getLocalHost();
            String hostname = addr.getHostName();
            System.out.println(addr.getHostAddress());
            System.out.println(hostname);
        }catch(UnknownHostException e)
        {
             //throw Exception
        }


    }
Run Code Online (Sandbox Code Playgroud)

}

  • 正如我上面提到的,这在Linux上提供了"127.0.0.1".但是,这可能适用于Windows系统... (3认同)