如何使用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);
}
答案 0 :(得分:1)
我相信你应该看一下Java的NetworkInterfaces类。 您将查询所有可用的接口并枚举它们以获取分配给每个接口的详细信息(在您的情况下为IP地址)。
您可以找到示例和解释Here
希望这有帮助
答案 1 :(得分:0)
试试这个,你可以得到
InetAddress address = InetAddress.getLocalHost();
NetworkInterface neti = NetworkInterface.getByInetAddress(address);
byte macadd[] = neti.getHardwareAddress();
System.out.println(macadd);
答案 2 :(得分: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");
}
}