如何在 Java 中在特定端口创建套接字

问题描述

如何在特定端口创建套接字?

解决方案

以下示例显示如何使用 Socket 类的 Socket 构造函数。以及如何使用 getLocalPort() getLocalAddress 、 getInetAddress() 和 getPort() 方法获取 Socket 详细信息。

import java.io.IOException;
import java.net.InetAddress;
import java.net.Socket;
import java.net.SocketException;
import java.net.UnknownHostException;

public class Main {
   public static void main(String[] args) {
      try {
         InetAddress addr = InetAddress.getByName("74.125.67.100");
         Socket theSocket = new Socket(addr, 80);
         System.out.println("Connected to " 
            + theSocket.getInetAddress()
            + " on port " + theSocket.getPort() + " from port "
            + theSocket.getLocalPort() + " of " 
            + theSocket.getLocalAddress());
      } catch (UnknownHostException e) {
         System.err.println("I can't find " + e  );
      } catch (SocketException e) {
         System.err.println("Could not connect to " +e );
      } catch (IOException e) {
         System.err.println(e);
      }
   }
}

结果

上述代码示例将产生以下结果。

Connected to /74.125.67.100 on port 80 from port 
2857 of /192.168.1.4
java_networking.html