3 回答

TA貢獻1859條經(jīng)驗 獲得超6個贊
我構(gòu)建了一個示例,該示例提取了源地址,目標(biāo)地址和接口地址。為簡便起見,沒有提供錯誤檢查。
// 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貢獻1872條經(jīng)驗 獲得超4個贊
為了提供O(1)查找,您需要將輔助控制結(jié)構(gòu)打包到提供O(1)查找的數(shù)據(jù)容器中。填充該結(jié)構(gòu)的數(shù)量至少為輔助控制消息的O(n)。您不必?fù)?dān)心要查找的控制消息的復(fù)雜性:總是只有少數(shù)幾個,并且只有您請求的那些。代您還需要零內(nèi)存管理。這是微不足道的開銷。
添加回答
舉報