http://www.mycplus.com/source-code/c-source-code/udp-sender-and-receiver/
http://www.winsocketdotnetworkprogramming.com/winsock2programming/winsock2advancedcode1e.html
http://msdn.microsoft.com/en-us/library/ms740566%28VS.85%29.aspx
Вот пример приложения и исходный код, который поможет вам.
изм:
Ниже приводится функция отправителя, которая принимает строку, размер строки, IP-адрес и порт и отправляет пакеты по UDP.
int sender(char cSendBuffer[], int iBufferSize, char cIP[], int iPort)
{
WSADATA wsaData;
WSAStartup(MAKEWORD(2,2), &wsaData);
char cBroadcast = '1';
int iNumBytes = 0;
struct sockaddr_in their_addr;
struct hostent *he;
SOCKET sock;
sock = socket(AF_INET,SOCK_DGRAM,0);
if(setsockopt(sock,SOL_SOCKET,SO_BROADCAST,&cBroadcast,sizeof(cBroadcast)) < 0)
{
printf("\n ----------------------------------------- \n");
printf("Error in setting UDP option");
printf("\n ----------------------------------------- \n");
return 0;
}//End if
their_addr.sin_family = AF_INET;
their_addr.sin_port = htons(iPort);
//Target IP
their_addr.sin_addr.s_addr = inet_addr (cIP);
int iSentBytes =0;
//Send bytes through socket
iSentBytes = sendto(sock,cSendBuffer, iBufferSize,0,(sockaddr*)&their_addr,sizeof(their_addr));
if( iSentBytes < 0)
{
printf("\n ----------------------------------------- \n");
printf("Data Sending Error");
printf("\n ----------------------------------------- \n");
closesocket(sock);
return 0;
}//End if
else
{
printf("\n ----------------------------------------- \n");
printf("\n Data sent successfully to AT PORT:%d AND IP:%s \n",iPort,cIP);
printf("\n ----------------------------------------- \n");
}//End else
closesocket(sock);
WSACleanup();
return 1;
}//End Function For Sending Packet
Ниже приводится функция приемника UDP.
int UDPReceiver( void )
{
char cRecievedBuffer[TRACK_BUFFER_SIZE];
WSADATA wsaData;
WSAStartup(MAKEWORD(2,2), &wsaData);
SOCKET sock;
sock = socket(AF_INET,SOCK_DGRAM,0);
// my address information
struct sockaddr_in my_addr;
// connector's address information
struct sockaddr_in their_addr;
//sizeof (ANSI C function)
int len = sizeof(struct sockaddr_in);
my_addr.sin_family = AF_INET;
my_addr.sin_port = htons(MYPORT);
//Automatically fill with my IP
my_addr.sin_addr.s_addr = INADDR_ANY;
if (bind(sock,(sockaddr*)&my_addr, sizeof (my_addr)) < 0)
{
printf("\n ----------------------------------------- \n");
printf(" Error in BINDING ");
printf("\n ----------------------------------------- \n");
return 0;
}//End if
while(recvfrom(sock,cRecievedBuffer,TRACK_BUFFER_SIZE,0,(sockaddr *)&their_addr,&len))
{
//Your Decoder code
}
}