如何使用Java获取客户端的LAN IP?

cra*_*giz 7 java ip lan ip-address

如何使用Java获取计算机的LAN IP地址?我想要连接到路由器和网络其余部分的IP地址.

我尝试过这样的事情:

Socket s = new Socket("www.google.com", 80);
String ip = s.getLocalAddress().getHostAddress();
s.close();
Run Code Online (Sandbox Code Playgroud)

这似乎适用于某些情况,但有时它会返回loopback-address或完全不同的东西.此外,它需要互联网连接.

有没有人有更准确的方法这样做?

编辑:认为这里问题比评论更好..

如果你有很多接口怎么办?例如,一个用于电缆,一个用于wifi,一个用于虚拟盒子等.是否无法真正看到哪一个连接到网络?

Ale*_*yak 15

试试java.net.NetworkInterface

import java.net.NetworkInterface;

...

for (
    final Enumeration< NetworkInterface > interfaces =
        NetworkInterface.getNetworkInterfaces( );
    interfaces.hasMoreElements( );
)
{
    final NetworkInterface cur = interfaces.nextElement( );

    if ( cur.isLoopback( ) )
    {
        continue;
    }

    System.out.println( "interface " + cur.getName( ) );

    for ( final InterfaceAddress addr : cur.getInterfaceAddresses( ) )
    {
        final InetAddress inet_addr = addr.getAddress( );

        if ( !( inet_addr instanceof Inet4Address ) )
        {
            continue;
        }

        System.out.println(
            "  address: " + inet_addr.getHostAddress( ) +
            "/" + addr.getNetworkPrefixLength( )
        );

        System.out.println(
            "  broadcast address: " +
                addr.getBroadcast( ).getHostAddress( )
        );
    }
}
Run Code Online (Sandbox Code Playgroud)


Dan*_*iel 7

起初:没有单一地址.您的机器至少有两个地址("lo"为127.0.0.1,"eth1"为192.168.1.1).

你想要这个:列出网络接口

正如您所料,您无法自动检测哪个路由器连接到哪个路由器,因为这需要对路由表进行复杂的解析.但是,如果您只是想要任何非本地地址,那么应该这样做.可以肯定的是,尝试在vista或Windows 7上至少使用一次,因为它们会添加IPv6地址.

import java.io.*;
import java.net.*;
import java.util.*;
import static java.lang.System.out;

public class ListNets 
{
    public static void main(String args[]) throws SocketException {
        Enumeration<NetworkInterface> nets = NetworkInterface.getNetworkInterfaces();
        for (NetworkInterface netint : Collections.list(nets))
            displayInterfaceInformation(netint);
    }

    static void displayInterfaceInformation(NetworkInterface netint) throws SocketException {
        out.printf("Display name: %s\n", netint.getDisplayName());
        out.printf("Name: %s\n", netint.getName());
        Enumeration<InetAddress> inetAddresses = netint.getInetAddresses();
        for (InetAddress inetAddress : Collections.list(inetAddresses)) {
            out.printf("InetAddress: %s\n", inetAddress);
        }
        out.printf("\n");
     }
}  
Run Code Online (Sandbox Code Playgroud)

以下是示例程序的示例输出:

Display name: bge0
Name: bge0
InetAddress: /fe80:0:0:0:203:baff:fef2:e99d%2
InetAddress: /121.153.225.59

Display name: lo0
Name: lo0
InetAddress: /0:0:0:0:0:0:0:1%1
InetAddress: /127.0.0.1
Run Code Online (Sandbox Code Playgroud)