I’ve been stuck at this issue for the last 4 days and I can’t seem to figure it out. I’m trying to send data to myself using UDP packets so another program can read the bytes.
I can clearly read the packets but I only get up to 3970 before the UDP portion of the program hangs. Glut and everything else continues to run fine. I gave my friend the same code and he ran it on his computer. He got 14386 iterations before it hangs. variable temp will count the number of packets sent. -1 is bad. counter counts the while loop iterations. I’m following the example here:
http://msdn.microsoft.com/en-us/library/ms740148(v=vs.85).aspx
Example Code:
#include "stdafx.h"
#include <WinSock2.h> // don't forget to add in
//Project Properties>Linker>Input>Additional Dependences [Ws2_32.lib]
sockaddr_in dest;
sockaddr_in local;
WSAData data;
static void SUDP_init(void)
{
printf("--[UDP Socket Initialized]--\r\n");
WSAStartup( MAKEWORD( 2, 2 ), &data );
local.sin_family = AF_INET;
local.sin_addr.s_addr = inet_addr( "127.0.0.1" ); //same as localhost
local.sin_port = 6000;
dest.sin_family = AF_INET;
dest.sin_addr.s_addr = inet_addr( "127.0.0.1" );
dest.sin_port = htons( 6000 );
bind( socket( AF_INET, SOCK_DGRAM, 0 ), (sockaddr *)&local, sizeof(local) );
printf("Socket Bound...\r\n");
}
static int counter = 0;
int _tmain(int argc, _TCHAR* argv[])
{
SUDP_init();
while(1){
char packet[30];
sprintf(packet, "%0.3f,%0.3f,%0.3f",
55.4,
16.1,
-27.88);
int temp = sendto( socket( AF_INET, SOCK_DGRAM, 0 ), packet, strlen(packet), 0, (sockaddr *)&dest, sizeof(dest) );
if(temp>=1){
counter++;
}
printf("Bytes Sent: %d, Counter: %d\r\n",temp,counter);
}
return 0;
}
You are allocating new sockets in a loop (the first argument to
sendto), you are also allocating another forbind, but these are never freed. You eventually run out of socket handles to allocate, hence your program hanging.Instead, allocate a socket once in
SUDP_init, store it instead of discarding it, then pass that tobindandsendto