Source with sendto() on unbound UDP socket?

Started by
5 comments, last by karx11erx 19 years, 1 month ago
Is there a way to find out the source IP address when calling sendto() on an unbound UDP socket (i.e. there was no bind() or connect() used on the socket)? Target OS: MS Windows (9x/ME/2K/XP), solution must work on all OS's listed.
_________karx11erxVisit my Descent site or see my case mod.
Advertisement
The OS will bind the socket to a random port for you when you do the sendto(). After that you can call getsockname() to find the bound address.
-Mike
Beware that when you're using getsockname(), the address you get back will very likely not mean anything to someone on the outside network, as there's likely a NAT between you and the destination.

Also, some systems may return INADDR_ANY for the IP address part, because, hey, it might have bound to all available interfaces.
enum Bool { True, False, FileNotFound };
Thank you. :)

The reason I am asking is that the client in my application needs to know the actual IP address its data was sent out from.

Is there a reliable way to find that out, except having the user enter it?
_________karx11erxVisit my Descent site or see my case mod.
Quote:Original post by karx11erx
The reason I am asking is that the client in my application needs to know the actual IP address its data was sent out from.

Is there a reliable way to find that out, except having the user enter it?
Why do you need it?
The problem is that due to NAT a single game server can have multiple IPs depending on how far "out" the client is.
You can always get the local IP or the global internet one through some service, but there's no safe way to determine it for intermediate levels.
If you absolutely require that information on the client end, have a message sent to the server and then have it send back the IP address that it "sees".

The IP address that the server sees may be different from the one that getsockname() returns, or even any of the IPs listed in the interface list.

In any case, using the interface list is not too helpful as the IP addresses could change during the lifetime of an application (think about a dial-up reconnecting, or DHCP changing the assigned address).

The source IP address isn't really too useful anyway - why do you need it?

Mark
I need it because each client checks the list of all clients the server it connects to for itself and choses its unique game id accordingly. If a client doesn't find itself, it thinks its not connected and quits from the match.

I didn't create that code, I am only trying to make it work with UDP/IP over the inet, so don't blame me. ;)

Well, I've found a way to get what I need, thanks for the input. I will indeed have the server place the destination (client) IP in the data, and the client will evaluate it.

[Edited by - karx11erx on March 15, 2005 3:19:34 PM]
_________karx11erxVisit my Descent site or see my case mod.

This topic is closed to new replies.

Advertisement