I have an application that is listening on 2 ports, it appears that when I call my function
WS_SetUpListener (see code below) with 2 different ports, I receive the same ListeningSocket for both, so when a packet arrives at either of the 2 ports, how can I tell what port it was sent to?
I call the function as follows:
ListeningSocket = WS_SetUpListener(port);
the code for it is:
SOCKET WS_SetUpListener(int port)
{
char port_buf[20] = {0};
struct addrinfo *result = NULL, hints;
SOCKET ListenSocket = INVALID_SOCKET;
//char recvbuf[DEFAULT_BUFLEN];
int iResult;
//int iSendResult;
int recvbuflen = DEFAULT_BUFLEN;
sprintf_s(port_buf, sizeof(port_buf), "%d", port);
ZeroMemory(&hints, sizeof (hints));
hints.ai_family = AF_INET;
hints.ai_socktype = SOCK_STREAM;
hints.ai_protocol = IPPROTO_TCP;
hints.ai_flags = AI_PASSIVE;
// Resolve the local address and port to be used by the server
iResult = getaddrinfo(NULL, port_buf, &hints, &result);
if (iResult != 0)
{
printf("getaddrinfo failed: %d\n", iResult);
return INVALID_SOCKET;
}
// Create a SOCKET for the server to listen for client connections
ListenSocket = socket(result->ai_family, result->ai_socktype, result->ai_protocol);
if (ListenSocket == INVALID_SOCKET)
{
printf("***ERROR*** at socket(): %ld\n", WSAGetLastError());
freeaddrinfo(result);
return INVALID_SOCKET;
}
// Set up the TCP listening socket
iResult = bind(ListenSocket, result->ai_addr, (int)result->ai_addrlen);
if (iResult == SOCKET_ERROR)
{
printf("bind failed: %d\n", WSAGetLastError());
freeaddrinfo(result);
closesocket(ListenSocket);
return INVALID_SOCKET;
}
freeaddrinfo(result);
iResult = listen(ListenSocket, SOMAXCONN);
if ( iResult == SOCKET_ERROR )
{
printf( "Error at bind(): %ld\n", WSAGetLastError() );
closesocket(ListenSocket);
return INVALID_SOCKET;
}
return ListenSocket;
}
What? The port number that you are listening on will not be the same port number that your remote peer will send you packets on. You would have to remember which port number you accepted the connection with.
Try using
getpeernameif you want to get the port number that you and your peer are using.