编程语言
首页 > 编程语言> > Java网络编程

Java网络编程

作者:互联网

网络编程


  1. 网络编程中存在两个主要的问题
    • 如何准确的定位网络上的一台或多台主机
    • 找到主机后如何进行通信
  2. 网络编程的要素
    • IP和端口号
    • 网络通信协议

IP


Java中的IP类:InetAddress

在Java中使用查找IP

public class IpAddressTest {
    public static void main(String[] args) {
        try {
            //查找本机地址
            InetAddress inetAddress1 = InetAddress.getByName("127.0.0.1");   //   /127.0.0.1
            System.out.println(inetAddress1);
            InetAddress inetAddress2 = InetAddress.getByName("localhost");   //   localhost/127.0.0.1
            System.out.println(inetAddress2);
            InetAddress inetAddress3 = InetAddress.getLocalHost();           //   DESKTOP-LIM1T42/172.18.1.164
            System.out.println(inetAddress3);

            //查询网站地址
            InetAddress inetAddress4 = InetAddress.getByName("www.baidu.com");   //   www.baidu.com/180.101.49.11
            System.out.println(inetAddress4);

            //常用方法
            System.out.println(inetAddress4.getAddress());
            System.out.println(inetAddress4.getHostAddress());
            System.out.println(inetAddress4.getCanonicalHostName());
            System.out.println(inetAddress4.getHostName());
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
    }
}

端口


端口表示一个计算机上程序的进程

在Java中使用端口

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

        System.out.println(isa.getAddress());
        System.out.println(isa.getHostName());
        System.out.println(isa.getHostString());
        System.out.println(isa.getPort());
    }
}

标签:Java,IP,编程,网络,System,println,InetAddress,isa,out
来源: https://blog.csdn.net/Yellow_Star___/article/details/118971810