// Server
#include <stdio.h>
#include <winsock.h>
#pragma comment(lib, "wsock32.lib")
int main(int argc, char* argv[])
{
WSADATA wsaData;
SOCKET sockListener;
SOCKADDR_IN sin, saUdpServ;
BOOL fBroadcast = TRUE;
char sendBuff[1024];
int nSize;
int nCount = 0;
if (WSAStartup(MAKEWORD(1, 1), &wsaData) != 0) // initialize WinSocket
{
printf("Failed to initialize windows socket!/n");
return -1;
}
sockListener = socket(PF_INET, SOCK_DGRAM, 0);
setsockopt(sockListener, SOL_SOCKET, SO_BROADCAST, (CHAR*)&fBroadcast, sizeof(BOOL));
sin.sin_family = AF_INET;
sin.sin_port = htons(0);
sin.sin_addr.s_addr = htonl(INADDR_ANY);
if (bind(sockListener, (SOCKADDR*)&sin, sizeof(sin)) != 0)
{
printf("failed to bind socket to local port!/n");
return -1;
}
saUdpServ.sin_family = AF_INET;
saUdpServ.sin_addr.s_addr = htonl(INADDR_BROADCAST);
saUdpServ.sin_port = htons(7001);
nSize = sizeof(SOCKADDR_IN);
while (true)
{
sprintf(sendBuff, "Message%d", nCount++);
sendto(sockListener, sendBuff, lstrlen(sendBuff), 0, (SOCKADDR*)&saUdpServ, sizeof(SOCKADDR_IN));
printf("%s/n", sendBuff);
}
return 0;
}


// client
#include <stdio.h>
#include <winsock.h>
#include <conio.h>
#pragma comment(lib, "wsock32.lib")
int main(int argc, char* argv[])
{
WSADATA wsaData;
SOCKET sockListener;
SOCKADDR_IN sin, saClient;
char cRecvBuff[1024];
int nSize, nbSize;
int iAddrLen = sizeof(saClient);
if (WSAStartup(MAKEWORD(1, 1), &wsaData) != 0)
{
printf("Failed to initialize windows socket!/n");
return -1;
}
sockListener = socket(AF_INET, SOCK_DGRAM, 0);
sin.sin_family = AF_INET;
sin.sin_port = htons(7001);
sin.sin_addr.s_addr = htonl(INADDR_ANY);
if (bind(sockListener, (SOCKADDR FAR*)&sin, sizeof(sin)) != 0)
{
printf("Failed to bind socket to local port!/n");
return -1;
}
while (true)
{
nSize = sizeof(SOCKADDR_IN);
if ((nbSize = recvfrom(sockListener, cRecvBuff, 1024, 0,
(SOCKADDR FAR*)&saClient, &nSize)) == SOCKET_ERROR)
{
printf("Receive Error!");
break;
}
cRecvBuff[nbSize] = '/0';
printf("%s/n", cRecvBuff);
}
return 0;
}