Reputation: 1759
I'm currently working on a networking assignment. We intended the client to automatically get assigned an IP and port to a TCP socket, and bind an UDP socket to the same address and port as the TCP socket. This way, both UDP and TCP share the same IP and port.
I've checked several questions here and all of them seem to state that the source port depends on the address you specify on binding the socket, however, this doesn't seem to work.
This is the code on my client, where I bind the UDP socket:
sockaddr_in udpAddress;
udpAddress.sin_family = AF_INET;
udpAddress.sin_addr.S_un.S_addr = htonl(INADDR_ANY);
udpAddress.sin_port = htons(27015);
bind(udpSocket, (sockaddr*)&udpAddress, sizeof(udpAddress));
printf("[UDP] Bound to port %d\n", ntohs(udpAddress.sin_port));
printf("Error when binding: %d\n", WSAGetLastError());
char buffer[32];
sprintf(buffer, "TEST\n");
sendto(udpSocket, buffer, 7, 0, (sockaddr*)&serverAddress, sizeof(serverAddress));
When running the application, this prints the following:
[UDP] Bound to port 27015
Error when binding: 0
Error 0 implies that there is no error, so this should be fine.
However, when I check on the server console, I see the following print:
[UDP] 127.0.0.1:64910
Which is generated by the following code:
#if PLATFORM == PLATFORM_WINDOWS
typedef int socklen_t;
#endif
sockaddr_in from;
socklen_t fromLength = sizeof(from);
short messageSize = recvfrom(udpSocket, (char*)udpBuffer, udpBufferSize, 0, (sockaddr*)&from, &fromLength);
if (messageSize > 0)
{
unsigned int from_address = ntohl(from.sin_addr.s_addr);
unsigned int from_port = ntohs(from.sin_port);
printf("[UDP] %d.%d.%d.%d:%d\n", from_address >> 24, from_address >> 16 & 0xff, from_address >> 8 & 0xff, from_address & 0xff, from_port);
}
I really wonder why this port is invalid. Does anyone know what I'm doing wrong?
Also worth saying, it seems like every time I restart my application, the port increments, so I'm not even sure if this is my own fault. If I send a packet to the server using the program PacketSender, the port reported on the server is the same port reported by the program, but this port is assigned automatically, not chosen.
Upvotes: 1
Views: 1011
Reputation: 1759
I have found the solution to my problem. When I tried to check for the return value of bind()
, I kept getting prompted with an error. It turns out that for whatever reason, I was in the std
namespace without explicitly stating this anywhere in my own code. After changing bind()
to ::bind()
, I was able to catch the return value and bind()
did what I expected.
Upvotes: 2