Take the 2-minute tour ×

I have a Visual Studio 2008 C++ application where I connect to a remote TCP server using a socket. The code looks basically like this:

SOCKET s = socket( AF_INET, SOCK_STREAM, 0 );
addrinfo* ai = getaddrinfo( ... );
connect( s, ai->ai_addr, sizeof( sockaddr_in ) );

Assuming my local client has multiple adapters, how can I tell which local interface was used to make the connection?

I realize I can use bind() to pick the adapter used, I'm curious about the case where I just let the system choose.

share|improve this question

1 Answer 1

up vote 3 down vote accepted

You can use getsockname to find out the address.

int getsockname(
  __in     SOCKET s,
  __out    struct sockaddr *name,
  __inout  int *namelen

struct sockaddr_in sin;
int sinlen = sizeof(sin);

getsockname(s, (strict sockaddr *)&sin, &sinlen);
share|improve this answer

Your Answer


