Note that there are some explanatory texts on larger screens.

plurals
  1. POC++ UDP. Why is recvfrom() is not blocking?
    text
    copied!<p>I am writing some simple client/server code using UDP. The program works fine, but if I only start the client, the recvfrom method does not block. However, when I remove the sendto method, recvfrom starts to block. Any idea of what is going on?</p> <p>Here is the client side code:</p> <pre><code> int server_length; /* Length of server struct */ char send_buffer[256] = "hi"; /* Data to send */ time_t current_time; /* Time received */ while(true) { /* Tranmsit data to get time */ server_length = sizeof(struct sockaddr_in); if (sendto(m_oSocket, send_buffer, (int)strlen(send_buffer) + 1, 0, (struct sockaddr *)&amp;m_oServer, server_length) == -1) { fprintf(stderr, "Error transmitting data.\n"); continue; } /* Receive time */ if (recvfrom(m_oSocket, (char *)&amp;current_time, (int)sizeof(current_time), 0, (struct sockaddr *)&amp;m_oServer, &amp;server_length) &lt; 0) { fprintf(stderr, "Error receiving data.\n"); continue; } /* Display time */ printf("Current time: %s\n", ctime(&amp;current_time)); Sleep(1000); } </code></pre> <p>And here is the initialization:</p> <pre><code>unsigned short m_iPortnumber; struct sockaddr_in m_oServer; struct sockaddr_in m_oClient; SOCKET m_oSocket; WSADATA w; /* Used to open Windows connection */ int a1, a2, a3, a4; /* Server address components in xxx.xxx.xxx.xxx form */ a1 = 192; a2 = 168; a3 = 2; a4 = 14; m_iPortnumber = 52685; /* Open windows connection */ if (WSAStartup(0x0101, &amp;w) != 0) { fprintf(stderr, "Could not open Windows connection.\n"); exit(0); } /* Open a datagram socket */ m_oSocket = socket(AF_INET, SOCK_DGRAM, 0); if (m_oSocket == INVALID_SOCKET) { fprintf(stderr, "Could not create socket.\n"); WSACleanup(); exit(0); } /* Clear out server struct */ memset((void *)&amp;m_oServer, '\0', sizeof(struct sockaddr_in)); /* Set family and port */ m_oServer.sin_family = AF_INET; m_oServer.sin_port = htons(m_iPortnumber); /* Set server address */ m_oServer.sin_addr.S_un.S_un_b.s_b1 = (unsigned char)a1; m_oServer.sin_addr.S_un.S_un_b.s_b2 = (unsigned char)a2; m_oServer.sin_addr.S_un.S_un_b.s_b3 = (unsigned char)a3; m_oServer.sin_addr.S_un.S_un_b.s_b4 = (unsigned char)a4; /* Clear out client struct */ memset((void *)&amp;m_oClient, '\0', sizeof(struct sockaddr_in)); /* Set family and port */ m_oClient.sin_family = AF_INET; m_oClient.sin_addr.s_addr=INADDR_ANY; m_oClient.sin_port = htons(0); /* Bind local address to socket */ if (bind(m_oSocket, (struct sockaddr *)&amp;m_oClient, sizeof(struct sockaddr_in)) == -1) { fprintf(stderr, "Cannot bind address to socket.\n"); closesocket(m_oSocket); WSACleanup(); exit(0); } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload