什么是网络interface?

网络interface是计算机与专用或公用网络之间的互连点。网络interface通常是网络interface卡(NIC),但不必具有物理形式。相反,网络interface可以用软件实现。例如,回送interface(IPv4 的127\.0\.0\.1和 IPv6 的::1)不是物理设备,而是模拟网络interface的软件。回送interface通常在测试环境中使用。

java.net.NetworkInterface类代表两种类型的interface。

NetworkInterface对于多宿主系统很有用,该系统是具有多个 NIC 的系统。使用NetworkInterface,可以指定用于特定网络活动的 NIC。

例如,假设您有一台具有两个配置的 NIC 的计算机,并且想要将数据发送到服务器。您可以这样创建一个套接字:

Socket soc = new java.net.Socket();
soc.connect(new InetSocketAddress(address, port));

要发送数据,系统将确定使用哪个interface。但是,如果您有首选项,或者需要指定要使用的 NIC,则可以在系统中查询适当的interface,并在要使用的interface上找到地址。创建套接字并将其绑定到该地址时,系统将使用关联的interface。例如:

NetworkInterface nif = NetworkInterface.getByName("bge0");
Enumeration<InetAddress> nifAddresses = nif.getInetAddresses();

Socket soc = new java.net.Socket();
soc.bind(new InetSocketAddress(nifAddresses.nextElement(), 0));
soc.connect(new InetSocketAddress(address, port));

您还可以使用NetworkInterface标识要在其上加入多播组的本地interface。例如:

NetworkInterface nif = NetworkInterface.getByName("bge0");
MulticastSocket ms = new MulticastSocket();
ms.joinGroup(new InetSocketAddress(hostname, port), nif);

除了此处介绍的两种用途外,NetworkInterface 还可通过其他多种方式与 Java API 一起使用。

首页