1

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?

syb0rg
  • 8,057
  • 9
  • 41
  • 81
chajka
  • 51
  • 2
  • 4
  • 13

3 Answers3

1

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

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
  • how Is it possible, if i am using this function -> int port= client.getPort();System.out.println("port:"+port); and getting port:63789, when i have server= new ServerSocket(5555); Socket clientSocket = new Socket("127.0.0.1", 5555); – chajka Apr 15 '13 at 01:18
  • 1
    Calling `Socket.getPort()` returns the **remote** port that the other party is using on their end, not the **local** port that the calling party is using. If you want the **local** port, use [`Socket.getLocalPort()`](http://docs.oracle.com/javase/7/docs/api/java/net/Socket.html#getLocalPort%28%29) instead. – Remy Lebeau Apr 15 '13 at 01:31
0

They use sockets.

Example:

Socket server = new ServerSocket(6666)
Socket connection = server.accept();
System.out.println("Connection received from " + connection.getInetAddress().getHostName());
Jeroen Vannevel
  • 43,651
  • 22
  • 107
  • 170
  • thx, server received:Connection received from genuine.microsoft.com, but if i want more precisely, like from IP:xxx.xxx.x.xxx and port:5555? – chajka Apr 15 '13 at 01:09
0

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

user207421
  • 305,947
  • 44
  • 307
  • 483