Get Server Name in TCP Server

2.2k views Asked by At

Is it possible to get the server address used by a TCP client? A client can reach the server using either IP address or host/domain name.

I'm trying to get the domain name using:

ServerSocket ss = new ServerSocket(port);
Socket s = ss.accept();
System.out.println(s.getLocalAddress().getHostName());
System.out.println(s.getLocalAddress().getCanonicalHostName());

but all I get is IP address, always!

In an HTTP server, we can achieve the same using httpServletRequest.getServerName(). It returns IP address if the HTTP client uses IP address and it returns domain name if the HTTP client uses domain name. So I'm quite sure it should be possible at TCP level also.

2

There are 2 answers

3
gabhijit On

If I understand your question correctly, you are trying to find out on server - which IP address was used by 'client' to connect to server, when server is listening on multiple IP Addresses. Is this your question? In that cases doing getsockname() on accepted socket should give you.

1
A.S On

if you tried your LocalHost as a server it will probably bring back the name, it might be a DNS problem tho; anyway try you localhost as a server and if it worked go to %SystemRoot%\system32\drivers\etc\hosts and define your host names.

check this out.

hope this will help.