Ok nevermind, I found the answer. For those of you who're interested, it's (obviously) quite logical:
INADDR_ANY means it will listen to all addresses that the current host owns, so it's impossible to do getsockname() on the listening socket (because it would have to store more than one sockaddr, for example one for 127.0.0.1 and one for your real IP). But when calling getsockname() on a new socket created by accept(), you will get the right IP address. Here's a little code to test it:
Code:
#include <stdio.h>
#include <winsock2.h>
int main() {
WSADATA wsaData;
if(WSAStartup(MAKEWORD(2,0),&wsaData) == -1)
return 0;
int sock;
if((sock = socket(AF_INET,SOCK_STREAM,IPPROTO_TCP)) == -1)
return 0;
struct sockaddr_in local;
local.sin_family = AF_INET;
local.sin_port = htons(1032);
local.sin_addr.s_addr = INADDR_ANY;
memset(&local.sin_zero,0,8);
if(bind(sock,(struct sockaddr *)&local,sizeof(struct sockaddr)) == -1)
return 0;
if(listen(sock,0) == -1)
return 0;
int saSize = sizeof(struct sockaddr);
getsockname(sock,(struct sockaddr *)&local,&saSize);
struct sockaddr_in remote;
int client;
while(client = accept(sock,(struct sockaddr *)&remote,&saSize)) {
getsockname(client,(struct sockaddr *)&local,&saSize);
printf("%s:%d\n",inet_ntoa(local.sin_addr),ntohs(local.sin_port));
close(client);
}
return 0;
}
When telnetting to localhost port 1032, it will give "127.0.0.1:1032". When telnetting to <my ip> port 1032, it will give "<my ip>:1032".