用vs c++ 写一个UDP发送自定义结构体
时间: 2023-08-04 16:36:02 浏览: 150
好的,下面是一个简单的示例代码,其中包括如何发送一个自定义的结构体:
```c++
#include <iostream>
#include <WinSock2.h>
#include <WS2tcpip.h>
#pragma comment(lib, "ws2_32.lib")
using namespace std;
struct MyStruct {
int id;
char name[20];
};
int main() {
// 初始化Winsock
WSADATA wsaData;
int iResult = WSAStartup(MAKEWORD(2, 2), &wsaData);
if (iResult != 0) {
cout << "WSAStartup failed with error: " << iResult << endl;
return 1;
}
// 创建套接字
SOCKET sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
if (sock == INVALID_SOCKET) {
cout << "socket failed with error: " << WSAGetLastError() << endl;
WSACleanup();
return 1;
}
// 设置接收方地址
sockaddr_in receiverAddr;
receiverAddr.sin_family = AF_INET;
receiverAddr.sin_port = htons(1234); // 设置端口号
inet_pton(AF_INET, "127.0.0.1", &receiverAddr.sin_addr); // 设置IP地址
// 构造自定义结构体并发送
MyStruct myStruct;
myStruct.id = 123;
strcpy_s(myStruct.name, "Test");
int sendSize = sendto(sock, (char*)&myStruct, sizeof(myStruct), 0, (sockaddr*)&receiverAddr, sizeof(receiverAddr));
if (sendSize == SOCKET_ERROR) {
cout << "sendto failed with error: " << WSAGetLastError() << endl;
closesocket(sock);
WSACleanup();
return 1;
}
// 清理
closesocket(sock);
WSACleanup();
return 0;
}
```
在这个例子中,我们首先初始化Winsock,然后创建一个UDP套接字。然后我们设置接收方地址,这里使用了本地IP地址和端口号为1234。接下来,我们构造了一个自定义的结构体MyStruct,并通过sendto函数发送给接收方。最后,我们清理并关闭套接字。
阅读全文