Java 获取linux计算机的所有IP地址

Java 获取linux计算机的所有IP地址,java,networking,Java,Networking,如何使用Java获取Linux机器的所有IP地址 我的设备有两个IP地址,但在尝试使用以下方法获取所有IP地址时,它将只返回一个主IP地址。同样的代码也适用于Windows InetAddress myAddr = InetAddress.getLocalHost(); System.out.println("myaddr::::" + myAddr.getHostName()); InetAddress localAddress[] = InetAddress.getAllByName(myA

如何使用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);
}
InetAddress myAddr=InetAddress.getLocalHost();
System.out.println(“myaddr::”+myaddr.getHostName());
InetAddress localAddress[]=InetAddress.getAllByName(myAddr.getHostName());
int len=localAddress.length;
对于(int i=0;i
我认为您应该看看Java的NetworkInterfaces类。 您将查询所有可用接口并对其进行枚举,以获得分配给其中每个接口的详细信息(在您的示例中为ip地址)

你可以找到例子和解释

希望这有帮助

试试这个,你可以

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

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");
 }
}  
import java.io.*;
导入java.net。*;
导入java.util.*;
导入静态java.lang.System.out;
公共类列表网{
公共静态void main(字符串args[])抛出SocketException、UnknownHostException{
System.out.println(System.getProperty(“os.name”);
枚举网络=NetworkInterface.getNetworkInterfaces();
用于(网络接口netint:Collections.list(nets))
显示接口信息(netint);
}
静态无效显示接口信息(NetworkInterface netint)引发SocketException{
out.printf(“显示名称:%s\n”,netint.getDisplayName());
out.printf(“名称:%s\n”,netint.getName());
枚举inetAddresses=netint.getInetAddresses();
用于(InetAddress:Collections.list(inetAddresses)){
out.printf(“InetAddress:%s\n”,InetAddress);
}
out.printf(“\n”);
}
}  
查看