欢迎光临散文网 会员登陆 & 注册

java网络编程InetAddress和InetSocketAddress

2022-09-03 09:12 作者:虚云幻仙  | 我要投稿

/**
* java网络编程
* 测试InetAddress类及InetSocketAddress类
* java中网络应用通信需要通过java.net包提供的网络功能间接调用操作系统接口
* InetAddress封装主机的ip地址和域名
*/

public class TestInetAddress {
   public static void main(String[] args) {
       try {
           InetAddress host = InetAddress.getLocalHost();
           //InetAddress类构造器私有,需要通过静态方法得到InetAddress对象
           //.getLocalHost()得到本地主机的InetAddress对象

           System.out.println(host.getHostAddress());
           //.getHostAddress()返回主机的ip地址字符串,结果为192.168.xxx.xxx私有/C类地址,非注册地址,内部使用。
           // 环回地址为127.xxx.xxx.xxx用于主机向自己发送通信,常用本机地址为127.0.0.1
           //目标地址为环回地址的数据在向下传递到网络层/IP层时不再向下传递,转发给本机IP层处理向上传递,绕开TCP/IP协议栈的下层,不会通过网卡发送出去

           System.out.println(host.getHostName());
           //.getHostName()返回主机名字符串,结果为LAPTOP-xxxxxx

           InetAddress baidu = InetAddress.getByName("www.baidu.com");
           //.getByName(String host)通过域名获取InetAddress对象,方法内部会进行域名解析
           System.out.println(baidu.getHostAddress());
           //返回百度网的ip地址39.156.66.18,ipv4地址为32位bit/4字节byte,字节之间用.分开
           System.out.println(baidu.getHostName());
           //.getHostName()返回hostName属性的值,如果在实例化InetAddress对象时使用String域名作为参数,则getHostName()返回该域名
           byte[] baiduIP = baidu.getAddress();
           //.getAddress()返回ip地址的字节数组byte[],39.156.66.18转换为[39, -100, 66, 18],byte从-128到127,156溢出-256=-100
           System.out.println(Arrays.toString(baiduIP));

           InetAddress baidu1 = InetAddress.getByAddress(baiduIP);
           //使用byte[]数组实例化InetAddress
           System.out.println(baidu1.getHostName());
           //通过ip地址实例化的对象.getHostName(),由于没有通过安全管理器security manager的安全检查security check,结果返回了ip地址39.156.66.14

           System.out.println(InetAddress.getByName("39.156.66.14").getHostName());
           //通过ip地址字符串实例化对象,getHostName()同样返回了ip地址
       } catch (UnknownHostException e) {
           throw new RuntimeException(e);
       }

       InetSocketAddress isa = new InetSocketAddress("www.baidu.com",80);
       //InetSocketAddress类与InetAddress类用法相近,可以用new实例对象,构造器中除了域名/ip地址以外需要额外指定port端口号
       //主机的端口号为16位,对应0-65535端口,是虚拟的概念,网络程序都有自己的端口, 80端口为http默认端口
       //socket套接字

       System.out.println(isa.getHostName());
       //作用同InetAddress,结果为:www.baidu.com
       InetAddress ia = isa.getAddress();
       //InetSocketAddress的.getAddress()方法返回InetAddress对象
       System.out.println(ia.getHostAddress());
   }
}

java网络编程InetAddress和InetSocketAddress的评论 (共 条)

分享到微博请遵守国家法律