Socket---简单测试和端口号获取

时间:2022-07-27 18:10:20
SocketAddress addr = new InetSocketAddress("172.20.33.70", 1080);
Proxy proxy = new Proxy(Proxy.Type.SOCKS, addr);
Socket socket = new Socket(proxy);
InetSocketAddress dest = new InetSocketAddress("baidu.com", 80);
try {
socket.connect(dest);
} catch (IOException e) {
e.printStackTrace();
}

/**
* 获得远程服务器的IP 地址.
*/
InetAddress inetAddress = socket.getInetAddress();
Log.d(TAG, "inetAddress = "+inetAddress);

/**
* 获得远程服务器的端口.
*/
int port = socket.getPort();
Log.d(TAG, "port = "+port);

/**
* 获得客户本地的IP 地址.
*/
InetAddress localAddress = socket.getLocalAddress();
Log.d(TAG, "localAddress = "+localAddress);

/**
* 获得客户本地的端口.
*/
int localPort = socket.getLocalPort();
Log.d(TAG, "localPort = "+localPort);

/**
* 获取本地的地址和端口号
*/
SocketAddress localSocketAddress = socket.getLocalSocketAddress();
Log.d(TAG, "localSocketAddress = "+localSocketAddress);

/**
* 获得远程的地址和端口号
*/
SocketAddress remoteSocketAddress = socket.getRemoteSocketAddress();
Log.d(TAG, "remoteSocketAddress = "+remoteSocketAddress);