How do servers get client's IP and port number

2019-06-08 13:53发布

问题:

In UDP I used:

InetAddress IPAddress = receivePacket.getAddress(); 

int port = receivePacket.getPort(); 

System.out.println ("From: " + IPAddress + ":" + port);
System.out.println ("Message: " + sentence);

I'm confused about TCP. How do servers get the client's IP and port number using TCP?

回答1:

Look at Socket.getInetAddress() and Socket.getPort().



回答2:

They use sockets.

Example:

Socket server = new ServerSocket(6666)
Socket connection = server.accept();
System.out.println("Connection received from " + connection.getInetAddress().getHostName());


回答3:

The source and destination IP address and port are present in every TCP segment or UDP datagram.



标签: java tcp