设置Winsock UDP套接字的步骤如下:
#include <winsock2.h>
#include <ws2tcpip.h>
WSAStartup
函数来完成。WSADATA wsaData;
int result = WSAStartup(MAKEWORD(2, 2), &wsaData);
if (result != 0) {
// 初始化失败,处理错误
}
socket
函数创建一个UDP套接字。SOCKET sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
if (sock == INVALID_SOCKET) {
// 创建套接字失败,处理错误
}
bind
函数将套接字绑定到一个本地地址和端口上。sockaddr_in localAddr;
localAddr.sin_family = AF_INET;
localAddr.sin_addr.s_addr = htonl(INADDR_ANY);
localAddr.sin_port = htons(0);
int bindResult = bind(sock, (SOCKADDR*)&localAddr, sizeof(localAddr));
if (bindResult == SOCKET_ERROR) {
// 绑定套接字失败,处理错误
}
sendto
和recvfrom
函数发送和接收UDP数据报。// 发送数据
sockaddr_in remoteAddr;
remoteAddr.sin_family = AF_INET;
remoteAddr.sin_addr.s_addr = inet_addr("192.168.0.1");
remoteAddr.sin_port = htons(12345);
char sendBuffer[] = "Hello, world!";
int sendResult = sendto(sock, sendBuffer, sizeof(sendBuffer), 0, (SOCKADDR*)&remoteAddr, sizeof(remoteAddr));
if (sendResult == SOCKET_ERROR) {
// 发送数据失败,处理错误
}
// 接收数据
char recvBuffer[1024];
sockaddr_in senderAddr;
int senderAddrSize = sizeof(senderAddr);
int recvResult = recvfrom(sock, recvBuffer, sizeof(recvBuffer), 0, (SOCKADDR*)&senderAddr, &senderAddrSize);
if (recvResult == SOCKET_ERROR) {
// 接收数据失败,处理错误
}
closesocket
函数关闭套接字。closesocket(sock);
WSACleanup
函数来清理Winsock库。WSACleanup();
这样,就完成了设置Winsock UDP套接字的步骤。
领取专属 10元无门槛券
手把手带您无忧上云