How to force a client in UDP to open a port when sending with sendto

I have a simple server and client in UDP (WinSocks / C ++).

I send the datagram client → server via sendto and respond from server to client using ip and port obtained from recvfrom function.

I learned that:

  • Each sender from the client is sent from a different port.
  • When you try to reply from a Windows server, it returns WSAECONNRESET (which means that the port is closed - http://support.microsoft.com/kb/263823 )

How can I correctly answer the client server (i.e. bind the forced port port to the client when sending using sendto?)

Edit: adding some source code:

bool InitClient() { internal->sock = socket(PF_INET, SOCK_DGRAM, 0); char8 yes = 1; setsockopt(internal->sock, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(int32)); return internal->sock != -1; } void Send(const IpAddress & target, const uint16 port, const char8 * data, int32 size ) { sockaddr_in trgt; memset(&trgt, 0, sizeof(trgt)); trgt.sin_family = AF_INET; trgt.sin_port = htons(port); trgt.sin_addr.s_addr = target.GetRaw(); if(sendto(internal->sock, (const char8 *)data, size, 0, (PSOCKADDR)&trgt, sizeof(trgt)) == SOCKET_ERROR) { LOG("Network sending error: %d", WSAGetLastError()); } } 
+1
udp sockets sendto
source share
1 answer

Call the bind function to specify the local port to send. An example of using port 4567 below. Be sure to check the return value from bind.Call this code after creating the socket.

 sockaddr_in local = {}; local.family = AF_INET; local.port = htons(4567); local.addr = INADDR_ANY; bind(internal->sock,(sockaddr*)&local, sizeof(local)); 

If you bind to port zero instead of 4567, then os will select a random port for you and will use it for all subsequent sending and receiving. You can call getsockname to find out which port has chosen for you after calling bind.

+4
source share

All Articles