Inet Address和Inet Socket Address类

2019/12/25 23:01
阅读数 30

Inet Address类:

封装计算机的IP地址,不包含端口号

 

 

Inet Socket Address类:

此类用于实现IP套接字地址(IP地址+端口号),用于socket通信

代码示例:

package aaa;

import java.net.InetAddress;
import java.net.UnknownHostException;

public class TestInetAddress {
public static void main(String[] args) throws UnknownHostException {
//获取Inet Address的方式
InetAddress ia = InetAddress.getLocalHost();
System.out.println("获取主机IP地址:"+ia.getHostAddress());
System.out.println("获取主机名:"+ia.getHostName());


//根据域名获取Inet Address对象
InetAddress ia2 = InetAddress.getByName("www.baidu.com");
System.out.println("百度服务器的IP地址:"+ia2.getHostAddress());
System.out.println("主机名称:"+ia2.getHostName());


//根据IP地址获取一个Inet Address对象
InetAddress ia3 = InetAddress.getByName("192.168.137.1");
System.out.println("服务器主机地址:"+ia3.getHostAddress());
System.out.println("主机名称:"+ia3.getHostName());
//如果IP地址不存在或者域名服务器(DNS)不允许IP地址和域名的映射,就会直接返回IP地址
}
}

 

 

 

Inet Socket Address类:

此类用于实现IP套接字地址(IP地址+端口号),用于socket通信

 

代码示例:

 

package aaa;

import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.UnknownHostException;

public class TestInetSocketAdderss {
public static void main(String[] args) throws UnknownHostException {
//创建对象
InetSocketAddress tsa1 = new InetSocketAddress("localhost",9999);
InetSocketAddress tsa2 = new InetSocketAddress("127.0.0.1",9999);
InetSocketAddress tsa3 = new InetSocketAddress("192.168.43.140",9999);


InetAddress ia = InetAddress.getByName("localhost");
InetSocketAddress tsa4 = new InetSocketAddress(ia,9999);
System.out.println("主机名称:"+tsa4.getHostName());
System.out.println("主机IP地址:"+tsa4.getAddress());


InetAddress ia2 = InetAddress.getByName("192.168.43.140");
InetSocketAddress tsa5 = new InetSocketAddress(ia2,9999);
System.out.println("主机名称:"+tsa5.getHostName());
System.out.println("主机IP地址:"+tsa5.getAddress());

}
}

展开阅读全文
打赏
0
0 收藏
分享
加载中
更多评论
打赏
0 评论
0 收藏
0
分享
返回顶部
顶部