【问题标题】:Get all ipaddress of a linux machine获取一台linux机器的所有ip地址
【发布时间】:2012-09-04 02:29:40
【问题描述】:

如何使用Java获取Linux机器的所有IP地址?

我的设备有两个 IP 地址,但在尝试使用以下方法获取所有 IP 地址时,它只会返回一个主 IP 地址。同一段代码适用于 Windows。

InetAddress myAddr = InetAddress.getLocalHost();
System.out.println("myaddr::::" + myAddr.getHostName());
InetAddress localAddress[] = InetAddress.getAllByName(myAddr.getHostName());
int len = localAddress.length;
for(int i = 0; i < len; i++)
{
  String localaddress = localAddress[i].getHostAddress().trim();
  System.out.println("localaddress::::" + localaddress);
}

【问题讨论】:

标签: java networking


【解决方案1】:

试试这个,

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, UnknownHostException {
     System.out.println(System.getProperty("os.name"));
     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");
 }
}  

【讨论】:

    【解决方案2】:

    试试这个,你可以得到

     InetAddress address = InetAddress.getLocalHost();
     NetworkInterface neti = NetworkInterface.getByInetAddress(address);
     byte macadd[] = neti.getHardwareAddress();
     System.out.println(macadd);
    

    【讨论】:

      【解决方案3】:

      我相信你应该看看 Java 的 NetworkInterfaces 类。 您将查询所有可用接口并枚举它们以获取分配给每个接口的详细信息(在您的情况下为 IP 地址)。

      你可以找到例子和解释Here

      希望对你有帮助

      【讨论】:

        猜你喜欢
        • 2011-07-13
        • 2010-09-17
        • 1970-01-01
        • 2023-03-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-09-04
        • 1970-01-01
        相关资源
        最近更新 更多