一.InetAddress實例獲取
1) InetAddress.getByName(String str) : 用主機名/Ip地址獲取Inetaddress對象
2) InetAddress.getByAddress(String hostname,byte[] b) : 用比特數組地址建立InetAddress, 該方法不用與dns交互,直接建立對象,適合新建dns上不存在的主機地址
3) InetAddress.getLocalHost(); 返回本機在dns上的主機名和地址
4) InetAddress[] --> InetAddress.getAllByName(String str) : 獲取dns上主機名映射的所有地址
二. 實例方法
1) getHostName() : 返回InetAddress中的主機名
2) toString() : 返字符串"主機名/ip地址"
3) getHostAddress() : 返回初始化InetAddress時的str
4) getCanonicalHostName() : 不從緩存中找hostAddress,重新連接DNS查找 : 61.135.169.125
三. NetworkInterface
1) 靜態方法:
NetworkInterface.getByName(String str) : 根據接口名,返回接口實例
NetworkInterface.getNetworkInterfaces() : 返回本機所有網絡接口
2) 實例方法
getInetAddresses() : 返回此網絡接口的InetAddress枚舉(多個實例)
getName() : 返回網絡接口的名字 (net27)
getDisplayName() : 更友好的返回網絡接口的名字 (Dell 無線 1397 WLAN Mini-Card-Native WiFi Filter Driver-0000)
public static void main(String[] args) {
try {
InetAddress add = InetAddress.getByName("www.baidu.com"); //當主機禁止主機名nds查找時,該方法報異常,可選擇getByAddress
System.out.println(add.getHostName()); //www.baidu.com
System.out.println(add.getHostAddress()); //61.135.169.125
System.out.println(add.getCanonicalHostName());//不從緩存中找hostAddress,重新連接DNS查找 : 61.135.169.125
byte[] b = add.getAddress(); //getAddress()獲取字節數組
System.out.println(b.length); //4,可用於判斷地址是ipv4還是ipv6(16字節地址)
InetAddress add2 = InetAddress.getByName("61.135.169.125");
System.out.println(add2.getHostName()); //61.135.169.125,返回初始化時的str
System.out.println(add2.getHostAddress()); //61.135.169.125
byte[] b1 = {107,23,(byte)216,(byte) 253};
InetAddress add3 = InetAddress.getByAddress("myComputer",b1);//該方法不用與dns交互,直接建立對象,適合新建dns上不存在的主機地址
System.out.println(add3); //myComputer/107.23.216.253
InetAddress[] addrs = InetAddress.getAllByName("www.baidu.com");
for(InetAddress addr:addrs){
System.out.println(addr);
// www.baidu.com/61.135.169.121
// www.baidu.com/61.135.169.125
}
InetAddress localhostOnDNS = InetAddress.getLocalHost(); //返回本機在dns上的主機名和地址
System.out.println(localhostOnDNS); //PC201403091545/192.168.1.18
Enumeration<NetworkInterface> e = NetworkInterface.getNetworkInterfaces(); //返回本機所有網絡接口
while(e.hasMoreElements()){
NetworkInterface ni = e.nextElement();
System.out.println(ni.getDisplayName());
System.out.println(ni.getName());
}
/* Dell 無線 1397 WLAN Mini-Card-Native WiFi Filter Driver-0000
net27
Dell 無線 1397 WLAN Mini-Card-WFP LightWeight Filter-0000
net28
Microsoft Virtual WiFi Miniport Adapter #9-Native WiFi Filter Driver-0000
net29
Microsoft Virtual WiFi Miniport Adapter #9-Liebao Wifi NAT Driver-0000
net30
*/
} catch (UnknownHostException e) {
System.out.println("目標不可達");
}catch (SocketException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}