地址及端口的控制

InetAddress

Dns:域名解析,将ip地址解析为英文字母

案例1:获取本机ip和名字

public static void main(String[] args) {
        try {
            InetAddress addr=InetAddress.getLocalHost();
            System.out.println(addr.getHostAddress());
            System.out.println(addr.getHostName());
            
            addr=InetAddress.getByName("www.baidu.com");
            System.out.println(addr.getHostAddress());
            System.out.println(addr.getHostName());
            
            addr=InetAddress.getByName("61.135.253.15");
            System.out.println(addr.getHostAddress());
            System.out.println(addr.getHostName());
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
    }

运行结果:

191.167.126.1
LAPTOP-D4D6919B
61.135.169.121
www.baidu.com
61.135.253.15
61.135.253.15

InetSocketAddress

用于把InetAddress加上端口进行封装

案例二:对本机网络进行封装

    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.getHostName());
        System.out.println(addr.getHostAddress());
    }

控制台:

steamcommunity.com
9999
steamcommunity.com
127.0.0.1

 

posted @ 2019-01-03 00:47  SteveYu  阅读(253)  评论(0编辑  收藏  举报