Java 网络工具类
1、NetworkInterface
使用NetworkInterface类获得网络接口信息,调用NetworkInterface.getNetworkInterfaces()获取所有网络接口,也可以调用NetworkInterface.getByName(String)通过名称获取网络接口。public static void main(String[] args) throws SocketException {2、InetAddress
Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
while (interfaces.hasMoreElements()) {
NetworkInterface ni = interfaces.nextElement();
System.out.println(ni);
}
}
使用InetAddress类来获得制定域名的地址信息,调用InetAddress.getByName(String)来获取地址,也可以调用InetAddress.getLocalHost()来获取本地地址。
public static void main(String[] args) throws UnknownHostException {
InetAddress addr = InetAddress.getByName("www.baidu.com");
System.out.println(addr.getHostName() + "/" + addr.getHostAddress());
addr = InetAddress.getLocalHost();
System.out.println(addr.getHostName() + "/" + addr.getHostAddress());
}