簡體   English   中英

如何使用Java獲取客戶端的LAN IP?

[英]How to get the LAN IP of a client using Java?

如何使用Java獲取計算機的LAN IP地址? 我想要連接到路由器和網絡其余部分的IP地址。

我嘗試過這樣的事情:

Socket s = new Socket("www.google.com", 80);
String ip = s.getLocalAddress().getHostAddress();
s.close();

這似乎適用於某些情況,但有時它會返回loopback-address或完全不同的東西。 此外,它需要互聯網連接。

有沒有人有更准確的方法這樣做?

編輯:認為這里問題比評論更好..

如果你有很多接口怎么辦? 例如,一個用於電纜,一個用於wifi,一個用於虛擬盒子等。 是否無法真正看到哪一個連接到網絡?

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

起初:沒有單一地址。 您的機器至少有兩個地址(“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");
     }
}  

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

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

這是我用了一段時間的方法。 它包括一個小的黑客,以找出外部可見的IP地址。

private List<String> getLocalHostAddresses() {

    List<String> addresses = new ArrayList<String>();

    try {
        Enumeration<NetworkInterface> e = NetworkInterface.getNetworkInterfaces();

        while (e.hasMoreElements()) {
            NetworkInterface ni = e.nextElement();
            Enumeration<InetAddress> e2 = ni.getInetAddresses();
            while (e2.hasMoreElements())
                addresses.add(e2.nextElement().getHostAddress());
        }
        URL u = new URL("http://whatismyip.org");
        BufferedReader in = new BufferedReader(new InputStreamReader(
                u.openStream()));
        addresses.add(in.readLine());
        in.close();
    } catch (Exception ignore) {
    }

    return addresses;
}

正如Daniel已經指出的那樣,你無法知道哪個界面是“連接”的。 例如,如果計算機有多個網絡接口卡都連接到不同的物理LAN,該怎么辦?

讓用戶決定使用哪個界面或全部嘗試,具體取決於您的用例。

try {
    InetAddress addr = InetAddress.getLocalHost();

    // Get IP Address
    byte[] ipAddr = addr.getAddress();

    // Get hostname
    String hostname = addr.getHostName();
} catch (UnknownHostException e) {
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM