IP地址与端口

前言:IP地址与端口可以唯一的确定处于网络中一个主机上的一个进程的位置,其中IP地址可以确定一台主机的地址,端口可以确定主机上进程的地址

IP地址与端口

IP地址

  • 确定网络上主机位置

获取网站域名对应IP地址

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

public class TestInetAddress {
    public static void main(String[] args) {
        try {
            //查询百度IP地址
            InetAddress inetAddress = InetAddress.getByName("www.baidu.com");
            System.out.println(inetAddress);
            //查询本机地址
            InetAddress inetAddress1 = InetAddress.getLocalHost();
            System.out.println(inetAddress1);
        } catch (UnknownHostException e){
            e.printStackTrace();
        }
    }
}

执行结果:

端口

  • 不同进程有不同端口号
  • 端口号范围为0~65535
  • 公有端口0~1023,分配给常见服务进程,如提供http协议,80端口
import java.net.InetSocketAddress;

public class TestInetSocketAdress {
    public static void main(String[] args) {
        InetSocketAddress socketAddress = new InetSocketAddress("127.0.0.1",8080);
        System.out.println(socketAddress);

        System.out.println(socketAddress.getAddress());
        System.out.println(socketAddress.getHostName());
        System.out.println(socketAddress.getPort());
    }
}
'''
posted @ 2020-05-25 21:08  Kuris101  阅读(634)  评论(0)    收藏  举报