我正在尝试以 UDP 格式发送数据(没有处理任何错误 - 只是打开套接字并发送数据)。使用的代码如下:
#include<iostream>
#include<arpa/inet.h>
#include<unistd.h>
#include<sys/socket.h>
#include<sys/types.h>
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
using namespace std;
int main()
{
int sockfd;
sockfd = socket(AF_INET,SOCK_DGRAM,0);
struct sockaddr_in client;
unsigned char* buffer = new unsigned char[1206]();
for(auto i=0; i<1206; i++){
buffer[i] = static_cast<unsigned char>(i);
}
client.sin_family = AF_INET;
client.sin_port = htons(5005);
client.sin_addr.s_addr = inet_addr("127.0.0.1");
socklen_t m = sizeof(client);
while(true){
sendto(sockfd,buffer,1206 ,0,(struct sockaddr *)&client,m);
cout<<"\nMessage sent...!! \n";
}
}
但是,这不被识别为 UDP 协议(protocol)。当尝试使用 wireshark 捕获它时,我得到以下结果。 (1206 字节的缓冲数据符合预期,但 44 字节的 header 应该是 42)。代码有什么问题?
最佳答案
您的代码运行良好(在 CentOS 7 和 gcc 4.8.5 上测试)。您使用的捕获方法是删除以太网、IP 和 UDP 层,只留下有效载荷。
关于c++ - UDP header 的填充量超出了预期 (42),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58081307/