2012-09-11 23 views
0

如何使用Java获取Linux机器的所有IP地址?获取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

看看[如何获得通过Java在Linux上的计算机的IP](http://stackoverflow.com/questions/901755/how-to-get-the-ip -of-the-computer-on-linux-through-java) – cubanacan

回答

1

我相信你应该采取NetworkInterfaces级Java的样子。 您将查询所有可用的接口并枚举它们以获取分配给每个接口的详细信息(您的案例中的IP地址)。

你可以找到例子和说明Here

希望这有助于

+0

它很好用,非常感谢 – mreaevnia

0

试试这个,你可以得到

InetAddress address = InetAddress.getLocalHost(); 
NetworkInterface neti = NetworkInterface.getByInetAddress(address); 
byte macadd[] = neti.getHardwareAddress(); 
System.out.println(macadd); 
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"); 
} 
}