如何通过Java获取linux上电脑的ip?

发布于 2024-07-20 08:15:27 字数 250 浏览 3 评论 0原文

如何通过Java获取linux下电脑的ip?

我在网上搜索了一些例子,我发现了一些有关 NetworkInterface 类的内容,但我无法理解如何获取 Ip 地址。

如果我同时运行多个网络接口,会发生什么情况? 将返回哪个 IP 地址。

我真的很感激一些代码示例。

PS:到目前为止,我一直使用 InetAddress 类,这对于跨平台应用程序来说是一个糟糕的解决方案。 (win/Linux)。

How to get the ip of the computer on linux through Java ?

I searched the net for examples, I found something regarding NetworkInterface class, but I can't wrap my head around how I get the Ip address.

What happens if I have multiple network interfaces running in the same time ? Which Ip address will be returned.

I would really appreciate some code samples.

P.S: I've used until now the InetAddress class which is a bad solution for cross-platform applications. (win/Linux).

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

破晓 2024-07-27 08:15:27

不要忘记环回地址,这些地址在外部是不可见的。 这是一个提取第一个非环回 IP(IPv4 或 IPv6)的函数

private static InetAddress getFirstNonLoopbackAddress(boolean preferIpv4, boolean preferIPv6) throws SocketException {
    Enumeration en = NetworkInterface.getNetworkInterfaces();
    while (en.hasMoreElements()) {
        NetworkInterface i = (NetworkInterface) en.nextElement();
        for (Enumeration en2 = i.getInetAddresses(); en2.hasMoreElements();) {
            InetAddress addr = (InetAddress) en2.nextElement();
            if (!addr.isLoopbackAddress()) {
                if (addr instanceof Inet4Address) {
                    if (preferIPv6) {
                        continue;
                    }
                    return addr;
                }
                if (addr instanceof Inet6Address) {
                    if (preferIpv4) {
                        continue;
                    }
                    return addr;
                }
            }
        }
    }
    return null;
}

Do not forget about loopback addresses, which are not visible outside. Here is a function which extracts the first non-loopback IP(IPv4 or IPv6)

private static InetAddress getFirstNonLoopbackAddress(boolean preferIpv4, boolean preferIPv6) throws SocketException {
    Enumeration en = NetworkInterface.getNetworkInterfaces();
    while (en.hasMoreElements()) {
        NetworkInterface i = (NetworkInterface) en.nextElement();
        for (Enumeration en2 = i.getInetAddresses(); en2.hasMoreElements();) {
            InetAddress addr = (InetAddress) en2.nextElement();
            if (!addr.isLoopbackAddress()) {
                if (addr instanceof Inet4Address) {
                    if (preferIPv6) {
                        continue;
                    }
                    return addr;
                }
                if (addr instanceof Inet6Address) {
                    if (preferIpv4) {
                        continue;
                    }
                    return addr;
                }
            }
        }
    }
    return null;
}
永不分离 2024-07-27 08:15:27

来自 Java 教程

为什么是 InetAddress< /code> 不是一个好的解决方案吗? 我在文档中没有看到有关跨平台兼容性的任何内容?

此代码将枚举所有网络接口并检索它们的信息。

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

From Java Tutorial

Why is InetAddress not a good solution? I don't see anything in the docs about cross platform compatibility?

This code will enumerate all network interfaces and retrieve their information.

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");
     }
}  

The following is sample output from the example program:

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

烂柯人 2024-07-27 08:15:27

这段代码在 4me 上有效:

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;


public class ShowIp {

    public static void main(String[] args) throws SocketException {
        NetworkInterface ni = NetworkInterface.getByName("eth0");
        Enumeration<InetAddress> inetAddresses =  ni.getInetAddresses();


        while(inetAddresses.hasMoreElements()) {
            InetAddress ia = inetAddresses.nextElement();
            if(!ia.isLinkLocalAddress()) {
                System.out.println("IP: " + ia.getHostAddress());
            }
        }
    }

}

This code worked 4me:

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;


public class ShowIp {

    public static void main(String[] args) throws SocketException {
        NetworkInterface ni = NetworkInterface.getByName("eth0");
        Enumeration<InetAddress> inetAddresses =  ni.getInetAddresses();


        while(inetAddresses.hasMoreElements()) {
            InetAddress ia = inetAddresses.nextElement();
            if(!ia.isLinkLocalAddress()) {
                System.out.println("IP: " + ia.getHostAddress());
            }
        }
    }

}
墨落成白 2024-07-27 08:15:27

只返回第一个非环回接口是不行的,因为它可能是由 Parallels 等软件创建的。 尝试钓鱼 eth0 是更好的选择。

static private InetAddress getIPv4InetAddress() throws SocketException, UnknownHostException {

    String os = System.getProperty("os.name").toLowerCase();

    if(os.indexOf("nix") >= 0 || os.indexOf("nux") >= 0) {   
        NetworkInterface ni = NetworkInterface.getByName("eth0");

        Enumeration<InetAddress> ias = ni.getInetAddresses();

        InetAddress iaddress;
        do {
            iaddress = ias.nextElement();
        } while(!(iaddress instanceof Inet4Address));

        return iaddress;
    }

    return InetAddress.getLocalHost();  // for Windows and OS X it should work well
}

It's not ok to just return the first non-loopback interface as it might have been created by some software like Parallels. It's a better bet to try fishing for the eth0.

static private InetAddress getIPv4InetAddress() throws SocketException, UnknownHostException {

    String os = System.getProperty("os.name").toLowerCase();

    if(os.indexOf("nix") >= 0 || os.indexOf("nux") >= 0) {   
        NetworkInterface ni = NetworkInterface.getByName("eth0");

        Enumeration<InetAddress> ias = ni.getInetAddresses();

        InetAddress iaddress;
        do {
            iaddress = ias.nextElement();
        } while(!(iaddress instanceof Inet4Address));

        return iaddress;
    }

    return InetAddress.getLocalHost();  // for Windows and OS X it should work well
}
浪漫人生路 2024-07-27 08:15:27

在我的例子中,最简单的解决方案是Socket.getLocalAddress()。 我必须专门为此目的打开套接字,但对于我的 Ubuntu 10.04 计算机上的所有网络接口,这是获取外部 IP 地址的唯一方法。

The simplest solution in my case was Socket.getLocalAddress(). I had to open the Socket specifically for that purpose, but with all the NetworkInterfaces on my Ubuntu 10.04 machine it was the only way to get the external IP address.

情绪少女 2024-07-27 08:15:27

我发现的最好的解决方案是在 linux / ubuntu 机器上运行命令。
所以我运行这个命令 hostname -I | 使用 java.cut -d' ' -f1

注意 - 方法的第二部分只是收集输出。

public String getIP() throws IOException
{
    ProcessBuilder pb = new ProcessBuilder("bash", "-c", "hostname -I | cut -d' ' -f1");

    Process process = pb.start();
    InputStream inputStream = process.getInputStream();
    Scanner scanner = new Scanner(inputStream, StandardCharsets.UTF_8);

    StringBuilder outputString = new StringBuilder();
    while (scanner.hasNextLine())
    {
        synchronized (this)
        {
            String message = scanner.nextLine();
            outputString.append(message);
            outputString.append("\n");
            log(message);
        }
    }
    scanner.close();

    return outputString.toString().trim();
}

The best solution i've found is to run command on linux / ubuntu machine.
So I run this command hostname -I | cut -d' ' -f1 using java.

note - second part of method is just to collect the output.

public String getIP() throws IOException
{
    ProcessBuilder pb = new ProcessBuilder("bash", "-c", "hostname -I | cut -d' ' -f1");

    Process process = pb.start();
    InputStream inputStream = process.getInputStream();
    Scanner scanner = new Scanner(inputStream, StandardCharsets.UTF_8);

    StringBuilder outputString = new StringBuilder();
    while (scanner.hasNextLine())
    {
        synchronized (this)
        {
            String message = scanner.nextLine();
            outputString.append(message);
            outputString.append("\n");
            log(message);
        }
    }
    scanner.close();

    return outputString.toString().trim();
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文