NetworkInterface 通过名字、InetAddress、getNetworkInterfaces获取网络接口

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

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();
		}
	}

   

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值