0

如何使用 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);
}
4

3 回答 3

1

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

您可以在此处找到示例和说明

希望这可以帮助

于 2012-09-11T08:49:10.340 回答
0

试试这个,你可以得到

 InetAddress address = InetAddress.getLocalHost();
 NetworkInterface neti = NetworkInterface.getByInetAddress(address);
 byte macadd[] = neti.getHardwareAddress();
 System.out.println(macadd);
于 2013-12-02T16:31:45.013 回答
0

试试这个,

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");
 }
}  
于 2016-03-03T08:57:18.880 回答