[英]Linux UDP recvfrom: What do I get at the start of my buffer?
如果我对recvfrom
调用返回有效字节数(例如1400
),我在缓冲区的开头会得到什么?
我有ethhdr
吗? 例如,即使我应该接收 UDP 数据包,此代码也不起作用:
void read_packets(struct config *cfg) {
int64_t read_bytes = recvfrom(cfg->socket_fd, buffer, BUFFER_SIZE, 0, NULL, NULL);
if(read_bytes == -1) {
return;
}
cfg->stats.amnt_of_packets += 1;
cfg->stats.amnt_of_bytes += read_bytes;
struct ethhdr *eth = (struct ethhdr*)(buffer);
if(ntohs(eth->h_proto) == ETH_P_IP) {
struct iphdr *iph = (struct iphdr*)(buffer + sizeof(struct ethhdr));
if(iph->protocol == IPPROTO_UDP) {
/* doesn't work */
}
}
}
socket_fd
被创建为:
cfg->socket_fd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
在 UDP 套接字上使用recvfrom
只会返回 UDP 数据包的有效负载,即发送端传递给sendto
。 您不会看到以太网标头、IP 标头或 UDP 标头作为其中的一部分。
但是,您确实为最后两个参数传递了 NULL 值。 这些可用于填充struct sockaddr_in
结构,该结构将包含发送方的 IP 地址和 UDP 端口。
此外,如果您使用recvmsg
,您可以从 IP 标头中获取某些字段的值,例如目标 IP 地址(如果套接字正在接收多播数据包,则很有用)、TOS/DSCP 字段或各种 IP 选项可以设置。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.