套接字地址
InetAddress类代表了一个网络目标地址,包括主机名和数字类型的地址信息。该类有两个子类,Inet4Address和 Inet6AddressInetAddress
实例是不可变的,一旦创建,每个实例就始终指向同一个地址NetworkInterface 类提供了访问主机所有接口的信息的功能。
package network;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.Enumeration;
public class InetAddressExample {
/**
* @param args
*/
public static void main(String[] args) {
try {
//获取网络接口列表
Enumeration<NetworkInterface> interfaceList = NetworkInterface
.getNetworkInterfaces();
if (interfaceList != null) {
while (interfaceList.hasMoreElements()) {
NetworkInterface iface = interfaceList.nextElement();
//getName,返回网络接口的本地名称,如:lo0"或"eth0
System.out.println("Interface " + iface.getName() + ":");
//获取网络接口相关联的地址
Enumeration<InetAddress> addrList = iface
.getInetAddresses();
while (addrList.hasMoreElements()) {
InetAddress inetAddr = addrList.nextElement();
//获取地址对应的主机名称和地址(数字标识)
System.out.println("addr: " + inetAddr.getHostName()
+ "\t" + inetAddr.getHostAddress());
}
}
}
InetAddress[] addresses = InetAddress.getAllByName("127.0.0.1");
for (InetAddress adr : addresses) {
System.out.println(adr.getHostName());
}
} catch (SocketException e) {
e.printStackTrace();
} catch (UnknownHostException e) {
e.printStackTrace();
}
}
}