Reputation: 1558
I need to get the local IP address that will be used for a tcp connection before establishing it (comparable to SIP's Contact in INVITE message). The initial message must contain my IP address and the used library requires the complete message before opening the connection.
Let's assume the server has 10.0.13.115 and my client has these IP addresses:
Is there a (simple) way to get the 10.0.14.33 other than opening a (dummy) connection to the server just to get the local interface used?
Edit: Thank you for the answers so far. I can neither change the server nor the protocol, so I really need the address on the client side. I will check whether I can have the network lib to be changed.
I was hoping there was a possibility as the OS / network stack also has to figure out the information...
Upvotes: 1
Views: 796
Reputation: 229344
The easiest, bar going through hoops of querying the local routing table and interfaces is:
connect()
an UDP socket to the destination, and learn the local address with getsockname()
.
Since it's an UDP socket, nothing is actually sent anywhere.
If the message you're sending is over the same TCP connection you establish, this is not needed though, as you naturally can just establish the TCP connection, get the local address with getsockname()
, use that address in the first "message" you send over that connection.
Upvotes: 2
Reputation: 29754
just connect via UDP socket (might be TCP also), read address via
int getsockname(int sockfd, struct sockaddr *addrsocklen_t *" addrlen );
and use this.
from linux man page:
getsockname() returns the current address to which the socket sockfd is bound, in the buffer pointed to by addr. The addrlen argument should be initialized to indicate the amount of space (in bytes) pointed to by addr. On return it contains the actual size of the socket address. The returned address is truncated if the buffer provided is too small; in this case, addrlen will return a value greater than was supplied to the call.
Return Value
On success, zero is returned. On error, -1 is returned, and errno is set appropriately.
Upvotes: 0
Reputation: 11798
Maybe it's no possible in your case, but nevertheless: the server gets to know the IP address when the connection is being established, it therefore is more like metadata than content. It should not be a big deal to get the sender IP address.
Upvotes: 1