Linux获取UDP目标地址,获取接收到的UDP报文的目的地址

我构建了一个示例,该示例提取了源地址,目标地址和接口地址。为简便起见,没有提供错误检查。

// 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

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值