udp_server.c
#include <stdio.h>
#include <winsock2.h>
#pragma comment(lib, "ws2_32.lib")
typedef struct sockaddr_in sockaddr_in ;
typedef struct sockaddr sockaddr;
int main(int argc, char* argv[])
{
WSADATA wsaData;
WORD sockVersion = MAKEWORD(2,2);
if(WSAStartup(sockVersion, &wsaData) != 0)
{
return 0;
}
SOCKET serSocket = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
if(serSocket == INVALID_SOCKET)
{
printf("socket error !");
return 0;
}
sockaddr_in serAddr;
serAddr.sin_family = AF_INET;
serAddr.sin_port = htons(8888);
serAddr.sin_addr.S_un.S_addr = INADDR_ANY;
if(bind(serSocket, (sockaddr *)&serAddr, sizeof(serAddr)) == SOCKET_ERROR)
{
printf("bind error !");
closesocket(serSocket);
return 0;
}
sockaddr_in remoteAddr;
int nAddrLen = sizeof(remoteAddr);
while (1)
{
char recvData[255];
int ret = recvfrom(serSocket, recvData, 255, 0, (sockaddr *)&remoteAddr, &nAddrLen);
//puts(recvData);
if (ret > 0)
{
recvData[ret] = 0x00;
printf("接受到一个连接:%s
", inet_ntoa(remoteAddr.sin_addr));
printf(recvData);
puts("");
}
int temp=strlen(recvData);
char sendData[255];
sprintf(sendData,"%d",temp);
//char * sendData = "一个来自服务端的UDP数据包
";
sendto(serSocket, sendData, strlen(sendData), 0, (sockaddr *)&remoteAddr, nAddrLen);
}
closesocket(serSocket);
WSACleanup();
return 0;
}
udp_client.c
#include <stdio.h>
#include <winsock2.h>
#pragma comment(lib, "ws2_32.lib")
typedef struct sockaddr_in sockaddr_in ;
typedef struct sockaddr sockaddr ;
int main(int argc, char* argv[])
{
WORD socketVersion = MAKEWORD(2,2);
WSADATA wsaData;
if(WSAStartup(socketVersion, &wsaData) != 0)
{
return 0;
}
SOCKET sclient = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
sockaddr_in sin;
sin.sin_family = AF_INET;
sin.sin_port = htons(8888);
sin.sin_addr.S_un.S_addr = inet_addr("127.0.0.1");
int len = sizeof(sin);
char sendData[256];
while(1)
{
gets(sendData);
//"来自客户端的数据包.
";
if(strcmp(sendData,"quit")==0)
break;
sendto(sclient, sendData, strlen(sendData), 0, (sockaddr *)&sin, len);
char recvData[255];
int ret = recvfrom(sclient, recvData, 255, 0, (sockaddr *)&sin, &len);
if(ret > 0)
{
recvData[ret] = 0x00;
printf(recvData);
puts("");
}
}
closesocket(sclient);
WSACleanup();
return 0;
}