Server 端:
WORD wVersion;
WSADATA wsaData;
sockaddr_in server_addr,client_addr;
char buff[1024];
wVersion=MAKEWORD(2,2);
if (WSAStartup(wVersion,&wsaData)!=0)
{
printf("无法加载 WSAStartup()!/n");
}
SOCKET server=socket(AF_INET,SOCK_DGRAM,0);
if (server==INVALID_SOCKET)
{
printf("The requested socket is invalid!/n");
}
server_addr.sin_family=AF_INET;
server_addr.sin_port=htons(5000);
server_addr.sin_addr.S_un.S_addr=INADDR_ANY;
bind(server,(sockaddr*)&server_addr,sizeof(server_addr));
int iLen=sizeof(client_addr);
while (1)
{
recvfrom(server,buff,sizeof(buff),0,(sockaddr*)&client_addr,&iLen);
printf("Client said: %s",buff);
strcpy(buff,"I am a server!!/n");
sendto(server,buff,sizeof(buff),0,(sockaddr*)&client_addr,sizeof(client_addr));
}
closesocket(server);
WSACleanup();
Client 端:
WORD wVersion=0x0202;
WSADATA wsaData;
sockaddr_in server_addr;
server_addr.sin_addr.S_un.S_addr=inet_addr("192.168.1.97");
server_addr.sin_family=AF_INET;
server_addr.sin_port=htons(5000);
char buff[1024];
int iLen=sizeof(server_addr);
if (WSAStartup(wVersion,&wsaData)!=0)
{
printf("WSAStartup Error!");
return 0;
}
SOCKET client=socket(AF_INET,SOCK_DGRAM,0);
if (client==INVALID_SOCKET)
{
printf("create socket fail!");
return 0;
}
strcpy(buff,"I am a client!/n");
sendto(client,buff,sizeof(buff),0,(sockaddr*)&server_addr,iLen);
recvfrom(client,buff,sizeof(buff),0,(sockaddr*)&server_addr,&iLen);
printf("Server Said: %s",buff);
closesocket(client);
WSACleanup();