C - TCP 校验和(使用原始套接字)--如何获取源 IP 地址
当使用原始套接字
发送TCP
数据时,允许将源IP地址
保留为零,以便内核输入正确的值。这很有帮助,尤其是在使用多个接口(具有不同的 IP
地址)时。
我现在的问题是:要计算 TCP
校验和,我需要知道源 IP 地址最终是什么。这对我来说似乎是不可能的事?
有没有办法确定我的传出数据包的源IP
?
(另一种方法是将我的原始套接字专门绑定到一个地址,但我不想这样做)。
/编辑:使用Linux
When using raw sockets
to send TCP
data, it is allowed to leave the source ip address
zero, so that the kernel puts in the correct value. This is helpful, especially when several interfaces (with different IP
addresses) are in use.
My problem is now: To calculate to TCP
checksum, I would need to know, what the source IP address is going to be in the end. This seems to be impossible to me?
Is there anyway to determine the source IP
of my outgoing packets?
(An alternative would be, to specifically bind my raw socket to an address, but I'd rather not want to do that).
/edit: Using Linux
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果你没有绑定你的套接字,内核必须根据目标地址找到源地址。
基本上完成了路由查找并确定了目标接口。之后,从该接口获取 IP:数据包的源。
因此,您的问题变成了执行路由查找,就像 ip route get 那样。
编辑
@nos提到使用不同的套接字(UDP)并将其连接到该目标地址。使用
getsockname
获取其本地绑定名称应该会为您提供将用于该目的地的源地址。If you don't bind your socket, the kernel has to find the source address based on the destination address.
Basically a route lookup is done and a destination interface determined. After that, the IP is taken from that interface: the source for your packet.
So your question turns into performing a route lookup, the way
ip route get
does.EDIT
@nos mentioned using a different socket (UDP) and connecting it to that destination address. Getting it's locally-bound name using
getsockname
should give you the source address that would be used for that destination.