Java学习笔记之--------网络编程之InetAddress

java.net.InetAddress:此类表示互联网协议 (IP) 地址。封装计算机的IP地址和DNS,没有端口。

getHostName():获取此IP地址的主机名。

getHostAddress():返回IP地址字符串(以文本表现形式)。

我们可以封装端口:

public class InetSocketDemo01 {
    public static void main(String[] args) {
        InetSocketAddress address = new InetSocketAddress("127.0.0.1",9999);
        System.out.println(address.getHostName());
        System.out.println(address.getPort());

        InetAddress addr = address.getAddress();
        System.out.println(addr.getHostAddress());
        System.out.println(addr.getHostName());
    }
}

输出结果为:

我们可以看到成功封装了端口。

还有其它一些使用,Demo如下:

public class InetDemo01 {
    public static void main(String[] args) throws UnknownHostException{
        //使用getLocalHost方法创建InetAddress对象
        InetAddress addr = InetAddress.getLocalHost();
        System.out.println(addr.getHostAddress());//返回:192.168.1.100
        System.out.println(addr.getHostName());//输出计算机名
        //根据域名得到InetAddress对象
        addr = InetAddress.getByName("www.163.com");
        System.out.println(addr.getHostAddress());//返回163服务器的ip:61.135.253.15
        System.out.println(addr.getHostName());//输出 www.163.com
        //根据ip得到InetAddress对象
        addr = InetAddress.getByName("61.135.253.15");
        System.out.println(addr.getHostAddress());//返回163服务器的ip:61.135.253.15
        System.out.println(addr.getHostName());//输出ip而不是域名。如果这个IP地址不存在或者DNS不解析,则返回域名
    }
}

以上为InetAddress类的用法介绍。

猜你喜欢

转载自blog.csdn.net/wangruoao/article/details/84029003