簡體   English   中英

無需連接到互聯網即可獲取本地IP地址

[英]Get local IP-Address without connecting to the internet

所以,我正在嘗試在我的本地網絡中獲取我的機器的IP地址(應該是192.168.178.41 )。

我的第一個意圖是使用這樣的東西:

InetAddress.getLocalHost().getHostAddress();

但它只返回127.0.0.1 ,這是正確的但對我沒有多大幫助。

我四處搜索並找到了這個答案https://stackoverflow.com/a/2381398/717341 ,它只是創建一個Socket -connection到一些網頁(例如“google.com”)並從套接字獲取本地主機地址:

Socket s = new Socket("google.com", 80);
System.out.println(s.getLocalAddress().getHostAddress());
s.close();

這適用於我的機器(它返回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());
    }
}

在我的機器上,這將返回以下內容:

name:eth1 (eth1)
fe80:0:0:0:226:4aff:fe0d:592e%3
192.168.178.41
name:lo (lo)

它找到我的網絡接口並返回所需的IP,但我不確定其他地址( fe80:0:0:0:226:4aff:fe0d:592e%3 )的含義。

另外,我還沒有找到一種方法來從返回的地址中過濾它(通過使用InetAddress isXX()方法),然后使用RegEx,我發現它非常“臟”。

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

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

如果您只關心IPv4,那么只需丟棄IPv6案例。 但要注意,IPv6是未來的^^。

PS:檢查你的一些break是否應該continue

這也是一種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();
}
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;
}
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
        }


    }

}

Yankee的答案對第一部分是正確的。 要打印出IP地址,您可以將其作為字節數組並將其轉換為正常的字符串表示形式,如下所示:

StringBuilder ip = new StringBuilder();
for(byte b : current_addr.getAddress()) {
    // The & here makes b convert like an unsigned byte - so, 255 instead of -1.
    ip.append(b & 0xFF).append('.');
}
ip.setLength(ip.length() - 1); // To remove the last '.'
System.out.println(ip.toString());

暫無
暫無

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

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