Socket编程(1)-InetAddress

来源:互联网 发布:数据流程分析 编辑:程序博客网 时间:2024/05/05 07:26

一.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查找时,该方法报异常,可选择getByAddressSystem.out.println(add.getHostName());//www.baidu.comSystem.out.println(add.getHostAddress());//61.135.169.125System.out.println(add.getCanonicalHostName());//不从缓存中找hostAddress,重新连接DNS查找 : 61.135.169.125byte[] 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,返回初始化时的strSystem.out.println(add2.getHostAddress());//61.135.169.125byte[] b1 = {107,23,(byte)216,(byte) 253};InetAddress add3 = InetAddress.getByAddress("myComputer",b1);//该方法不用与dns交互,直接建立对象,适合新建dns上不存在的主机地址System.out.println(add3);//myComputer/107.23.216.253InetAddress[] 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.18Enumeration<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-0000net27Dell 无线 1397 WLAN Mini-Card-WFP LightWeight Filter-0000net28Microsoft Virtual WiFi Miniport Adapter #9-Native WiFi Filter Driver-0000net29Microsoft Virtual WiFi Miniport Adapter #9-Liebao Wifi NAT Driver-0000net30 */} catch (UnknownHostException e) {System.out.println("目标不可达");}catch (SocketException e) {// TODO Auto-generated catch blocke.printStackTrace();}}


0 0
原创粉丝点击