NetworkInterface
1. 通过网络接口名获取网络接口
public static void netWorkInterfaceByName(){
try{
NetworkInterface ni = NetworkInterface.getByName("eth0");
if(ni == null){
System.out.println("no such interface IKEv2");
}else{
System.out.println(ni);
}
}catch(Exception e){
System.out.println("could not list sockets");
}
}
![]()
2. 通过ip获取InetAddress,通过InetAddress获取NetworkInterface
public static void networkInterfaceByAddress(){
try {
InetAddress inet = InetAddress.getByName("127.0.0.1");
NetworkInterface ni = NetworkInterface.getByInetAddress(inet);
if(ni == null){
System.out.println("没有本地回送接口");
}else{
System.out.println(ni);
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
![]()
3. 通过getNetworkInterfaces()获取所有的网络接口
public static void getAllNetworkIntefaces(){
try {
Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
while(interfaces.hasMoreElements()){
NetworkInterface inte = interfaces.nextElement();
System.out.println(inte);
}
} catch (SocketException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

本文介绍如何使用Java进行网络编程,包括通过网络接口名、IP地址获取网络接口信息,以及获取所有网络接口的方法。提供了详细的代码示例,帮助读者理解并应用。
1644





