C语言 windows下运行UDP服务端
时间: 2024-05-11 16:17:31 浏览: 89
下面是一个简单的C语言代码,可以在Windows下运行UDP服务端:
```c
#include <stdio.h>
#include <winsock2.h>
#pragma comment(lib,"ws2_32.lib") //加载 ws2_32.dll
int main()
{
//初始化DLL
WSADATA wsaData;
WSAStartup(MAKEWORD(2, 2), &wsaData);
//创建套接字
SOCKET serverSocket = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
//设置服务器地址
SOCKADDR_IN serverAddr;
serverAddr.sin_family = AF_INET;
serverAddr.sin_port = htons(8888);
serverAddr.sin_addr.S_un.S_addr = htonl(INADDR_ANY);
//绑定套接字和地址
bind(serverSocket, (SOCKADDR*)&serverAddr, sizeof(serverAddr));
//接收数据
char recvBuf[1024];
SOCKADDR_IN clientAddr;
int len = sizeof(clientAddr);
int ret = recvfrom(serverSocket, recvBuf, sizeof(recvBuf), 0, (SOCKADDR*)&clientAddr, &len);
printf("Received: %s\n", recvBuf);
//发送数据
char sendBuf[] = "Hello, World!";
ret = sendto(serverSocket, sendBuf, sizeof(sendBuf), 0, (SOCKADDR*)&clientAddr, len);
printf("Sent: %s\n", sendBuf);
//关闭套接字
closesocket(serverSocket);
//清理DLL
WSACleanup();
return 0;
}
```
该代码使用Windows Socket API来实现UDP服务端。首先,需要调用WSAStartup函数来初始化Winsock库。然后,创建一个UDP套接字,使用bind函数将套接字绑定到本地地址和端口号。接着,使用recvfrom函数从客户端接收数据,并使用sendto函数向客户端发送数据。最后,调用closesocket函数关闭套接字并调用WSACleanup函数清理Winsock库。
阅读全文