3 回答
TA贡献1818条经验 获得超7个赞
我构建了一个示例,该示例提取了源地址,目标地址和接口地址。为简便起见,没有提供错误检查。
// sock is bound AF_INET socket, usually SOCK_DGRAM
// include struct in_pktinfo in the message "ancilliary" control data
setsockopt(sock, IPPROTO_IP, IP_PKTINFO, &opt, sizeof(opt));
// the control data is dumped here
char cmbuf[0x100];
// the remote/source sockaddr is put here
struct sockaddr_in peeraddr;
// if you want access to the data you need to init the msg_iovec fields
struct msghdr mh = {
.msg_name = &peeraddr,
.msg_namelen = sizeof(peeraddr),
.msg_control = cmbuf,
.msg_controllen = sizeof(cmbuf),
};
recvmsg(sock, &mh, 0);
for ( // iterate through all the control headers
struct cmsghdr *cmsg = CMSG_FIRSTHDR(&mh);
cmsg != NULL;
cmsg = CMSG_NXTHDR(&mh, cmsg))
{
// ignore the control headers that don't match what we want
if (cmsg->cmsg_level != IPPROTO_IP ||
cmsg->cmsg_type != IP_PKTINFO)
{
continue;
}
struct in_pktinfo *pi = CMSG_DATA(cmsg);
// at this point, peeraddr is the source sockaddr
// pi->ipi_spec_dst is the destination in_addr
// pi->ipi_addr is the receiving interface in_addr
}
TA贡献1831条经验 获得超9个赞
为了提供O(1)查找,您需要将辅助控制结构打包到提供O(1)查找的数据容器中。填充该结构的数量至少为辅助控制消息的O(n)。您不必担心要查找的控制消息的复杂性:总是只有少数几个,并且只有您请求的那些。代您还需要零内存管理。这是微不足道的开销。
- 3 回答
- 0 关注
- 955 浏览
添加回答
举报