package org.zhangmeng.test.eg_socket;
import java.net.Inet4Address;
import java.net.Inet6Address;
import java.net.InetAddress;
import java.net.InterfaceAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;
/***
* InetAddress
* 主机名必须被解析为数字型地址才能用来通信
* 网络目标地址 ,包括主机名和数字类型地址信息。
* 两个子类 :Inet4Address Inet6Address
* InetAddress 创建和访问
* static InetAddress[ ] getAllByName(String host)
* static InetAddress getByName(String host)
* static InetAddress getLocalHost()
* byte[] getAddress() 地址的二进制形式
* InetAddress 字符串表示方法
* String toString() ep:"hostname.example.com/192.0.2.127" "never.example.net/2000::620:1a30:95b2 "
* String getHostAddress()
* String getHostName()
* String getCanonicalHostName()
* InetAddress 检测属性
* boolean isAnyLocalAddress()
* boolean isLinkLocalAddress()
* boolean isLoopbackAddress()
* boolean isMulticastAddress() 是否多播地址
* boolean isMCGlobal()
* boolean isMCLinkLocal()
* boolean isMCNodeLocal()
* boolean isMCOrgLocal()
* boolean isMCSiteLocal()
* boolean isReachable(int timeout) 是否可以进行数据交换
* boolean isReachable(NetworkInterface netif, int ttl, int timeout)
*
* NetworkInterface创建,获取信息
* static Enumeration<NetworkInterface> getNetworkInterfaces()
* static NetworkInterface getByInetAddress(InetAddress addr)
* static NetworkInterface getByName(String name)
* Enumeration<InetAddress> getInetAddresses()
* String getName() 接口的名字 ep : lo0 代表回环地址的name
* String getDisplayName()
*/
public class InetAddressExample {
public static void main(String[] args) {
try {
//主机上的所有的网络接口
Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces();
if(networkInterfaces == null){
System.out.println("--No interfaces found--");
}else{
while(networkInterfaces.hasMoreElements()){
NetworkInterface iface = networkInterfaces.nextElement();
//接口名字
System.out.println("Interface " + iface.getName() + ":");
//接口相关地址
Enumeration<InetAddress> inetAddresses = iface.getInetAddresses();
if(!inetAddresses.hasMoreElements()){
System.out.println("\tNo addresses for this interface");
}else{
//遍历接口相关地址信息
while(inetAddresses.hasMoreElements()){
InetAddress address = inetAddresses.nextElement();
System.out.println("\tAddress " + (address instanceof Inet4Address ? "(v4)" : (address instanceof Inet6Address ? "(v6)" : "(?)")));
System.out.println(":" + address.getHostAddress());
}
}
}
}
} catch (SocketException e) {
e.printStackTrace();
}
String hosts[] = {"www.baidu.com"};
for(String host : hosts){
try{
System.out.println(host + ":");
InetAddress[] addressList = InetAddress.getAllByName(host);
for(InetAddress address : addressList){
System.out.println("\t" + address.getHostName() + "/" + address.getHostAddress());
System.out.println(address.getCanonicalHostName());
}
}catch(Exception e){
e.printStackTrace();
}
}
}
}
1、NetworkInterface and InetAddress
最新推荐文章于 2022-06-20 20:26:49 发布