tier1
tier1

Reputation: 6433

C TCP Socket - Get packet destination name

This is more hypothetical at this point but lets say I have a TCP server written in C running on Linux. Is it possible to obtain the destination name from an individual packet? For example, if client connects and my server is located at www.example.com. I would like to be able to obtain "www.example.com" from the incoming packet.

My end goal is to separate network traffic by destination name similar to the way that IIS does on Windows with bindings for websites.

It would be nice to have multiple services running on the same machine and be accessible through the same port: 443, but be able to be separated by domain name. If I can obtain the destination name from the packet, I'm pretty sure that I can write something like this fairly easily.

--Edit I have done a little bit of research but have come up empty. I've looked through previous servers that I have written and I don't think I can do it with the existing Linux socket layer. I might have to go lower than that.

Upvotes: 1

Views: 1389

Answers (3)

David Schwartz
David Schwartz

Reputation: 182743

If the protocol the client is using supports this, then it's possible. If not, then it's not possible. TCP doesn't provide any way to obtain the host name the client was originally trying to reach, but some other protocols (such as HTTP and TLS) do.

Upvotes: 1

John Bollinger
John Bollinger

Reputation: 180058

If you have a TCP server for Linux, written in C, then at some level it will be using the accept() syscall to accept incoming connections. Once a connection is made, all packets received from and sent to its corresponding socket are associated with the same remote machine. The address of that remote machine is provided to the accept() caller via the second argument to that call.

You may be able to look up the address via gethostbyaddr().

Upvotes: 1

Roddy
Roddy

Reputation: 68023

No, because the destination hostname is never sent.

The sender uses DNS to find the IP address for the host it wants to communicate with, then sends a packet to that IP address. (Lower level still, the IP address is translated to a MAC address, which is what the hardware layer uses)

Your TCP sockets layer should allow you to see the source and destination IP addresses for the socket, and you'd then have to do a reverse-DNS lookup to translate that back to a hostname. But remember that one IP address could translate to multiple host names...

Upvotes: 3

Related Questions