由NetworkInterface获得接口和ip地址。支持多网卡,多ip地址。linux和windows通用。
//---------------------------------ipdisplay.java----------------------------------------
import java.net.InetAddress;
import java.util.Enumeration;
import java.net.NetworkInterface;
import java.util.*;
public class ipdisplay {
/**
* @param args
* @throws Exception
*/
public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub
String allipaddress;
ArrayList ar = new ArrayList();
Enumeration netInterfaces = NetworkInterface.getNetworkInterfaces();
while (netInterfaces.hasMoreElements()) {
NetworkInterface ni = (NetworkInterface) netInterfaces.nextElement();
Enumeration cardipaddress = ni.getInetAddresses();
InetAddress ip = (InetAddress) cardipaddress.nextElement();
if(!ip.getHostAddress().equalsIgnoreCase("127.0.0.1") )
{ ar.add(ni.getName()+":");
allipaddress=ip.getHostAddress();
while(cardipaddress.hasMoreElements())
{
ip = (InetAddress) cardipaddress.nextElement();
allipaddress=allipaddress+" , "+ip.getHostAddress();
}
ar.add(allipaddress);
}
else
continue;
}
for(int i=0;i<ar.size();)
{
System.out.println(ar.get(i++));
}
}
}
//-------------------------------------------------------------------------------------------------
结果如下
eth0:
192.168.88.1
eth1:
192.168.161.1
eth2:
192.168.2.19 , 192.168.0.18 , 192.168.10.18
ppp0:
222.183.146.3
//---------------------------------ipdisplay.java----------------------------------------
import java.net.InetAddress;
import java.util.Enumeration;
import java.net.NetworkInterface;
import java.util.*;
public class ipdisplay {
/**
* @param args
* @throws Exception
*/
public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub
String allipaddress;
ArrayList ar = new ArrayList();
Enumeration netInterfaces = NetworkInterface.getNetworkInterfaces();
while (netInterfaces.hasMoreElements()) {
NetworkInterface ni = (NetworkInterface) netInterfaces.nextElement();
Enumeration cardipaddress = ni.getInetAddresses();
InetAddress ip = (InetAddress) cardipaddress.nextElement();
if(!ip.getHostAddress().equalsIgnoreCase("127.0.0.1") )
{ ar.add(ni.getName()+":");
allipaddress=ip.getHostAddress();
while(cardipaddress.hasMoreElements())
{
ip = (InetAddress) cardipaddress.nextElement();
allipaddress=allipaddress+" , "+ip.getHostAddress();
}
ar.add(allipaddress);
}
else
continue;
}
for(int i=0;i<ar.size();)
{
System.out.println(ar.get(i++));
}
}
}
//-------------------------------------------------------------------------------------------------
结果如下
eth0:
192.168.88.1
eth1:
192.168.161.1
eth2:
192.168.2.19 , 192.168.0.18 , 192.168.10.18
ppp0:
222.183.146.3