The Java Tutorials have been written for JDK 8.Java教程是为JDK 8编写的。Examples and practices described in this page don't take advantage of improvements introduced in later releases and might use technology no longer available.本页中描述的示例和实践没有利用后续版本中引入的改进,并且可能使用不再可用的技术。See Java Language Changes for a summary of updated language features in Java SE 9 and subsequent releases.有关Java SE 9及其后续版本中更新的语言特性的摘要,请参阅Java语言更改。
See JDK Release Notes for information about new features, enhancements, and removed or deprecated options for all JDK releases.有关所有JDK版本的新功能、增强功能以及已删除或不推荐的选项的信息,请参阅JDK发行说明。
A network interface is the point of interconnection between a computer and a private or public network. A network interface is generally a network interface card (NIC), but does not have to have a physical form. Instead, the network interface can be implemented in software. For example, the loopback interface (127.0.0.1 for IPv4 and ::1 for IPv6) is not a physical device but a piece of software simulating a network interface. The loopback interface is commonly used in test environments.
The java.net.NetworkInterface
class represents both types of interfaces.
NetworkInterface is useful for a multi-homed system, which is a system with multiple NICs. Using NetworkInterface
, you can specify which NIC to use for a particular network activity.
For example, assume you have a machine with two configured NICs, and you want to send data to a server. You create a socket like this:
Socket soc = new java.net.Socket(); soc.connect(new InetSocketAddress(address, port));
To send the data, the system determines which interface is used. However, if you have a preference or otherwise need to specify which NIC to use, you can query the system for the appropriate interfaces and find an address on the interface you want to use. When you create the socket and bind it to that address, the system uses the associated interface. For example:
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));
You can also use NetworkInterface
to identify the local interface on which a multicast group is to be joined. For example:
NetworkInterface nif = NetworkInterface.getByName("bge0"); MulticastSocket ms = new MulticastSocket(); ms.joinGroup(new InetSocketAddress(hostname, port), nif);
NetworkInterface can be used with Java APIs in many other ways beyond the two uses described here.