java中通过网卡名称获取IP地址
package me.xuzs.sso.test;
import java.net.inetaddress;
import java.net.networkinterface;
import java.net.socketexception;
import java.util.enumeration;
public class internettest {
public static void main(string[] args) {
string netcard = "lo";
try {
enumeration<networkinterface> netinterfaces = networkinterface
.getnetworkinterfaces();
if (netinterfaces.hasmoreelements()) {
networkinterface netinterface = netinterfaces.nextelement();
if (netcard.equals(netinterface.getname())) {
// 子接口,linux下会取到父接口??
enumeration<networkinterface> subnetinterfaces = netinterface
.getsubinterfaces();
while (subnetinterfaces.hasmoreelements()) {
networkinterface subnetinterface = subnetinterfaces
.nextelement();
system.out.println(subnetinterface.getname());
enumeration<inetaddress> subaddresses = netinterface
.getinetaddresses();
while (subaddresses.hasmoreelements()) {
inetaddress subaddress = subaddresses.nextelement();
system.out.println(subaddress.gethostaddress());
}
}
// 打印接口下所有ip
system.out.println(netinterface.getname());
enumeration<inetaddress> addresses = netinterface
.getinetaddresses();
while (addresses.hasmoreelements()) {
inetaddress address = addresses.nextelement();
system.out.println(address.gethostaddress());
}
}
}
} catch (socketexception e) {
e.printstacktrace();
}
}
}