【发布时间】:2014-04-03 17:59:01
【问题描述】:
这有点难以解释,所以请耐心等待。
在python中,我想发送一个UDP消息:
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.bind(('0.0.0.0', 5011))
dest = ('foo.horse', 5011)
# attact the source address to the message
...
sock.sendto(msg, dest)
但是在我发送该消息之前,我想根据目标地址确定将要发送的接口的地址,以便我可以将其包含在消息中。
例如,如果目标是 WAN 地址,则它将是 LAN 接口的地址(因为我在 NAT 后面)。如果目的地是“localhost”,那么地址就是“127.0.0.1”。如果它是 VPN 上的地址,那么它将是我的 VPN 地址。
更新:
看起来我可以使用:$ ip route get <destination>,它会告诉我源地址
https://stackoverflow.com/a/5557459/334632
我最终深入研究了 iproute2 源代码,但我看不到它在使用什么我可以快捷方式。 https://git.kernel.org/cgit/linux/kernel/git/shemminger/iproute2.git/tree/ip/iproute.c#n1376
我最终可能只是创建一个子进程并解析结果,但如果可能的话,我想避免这种情况。
【问题讨论】:
-
为什么?您无需将其放入消息中。无论如何,它对接收者都是可用的。
-
@EJP SIP Via header。似乎某些 SIP 应用程序能够做到这一点,但我不知道他们是如何做到的。
标签: python linux sockets networking udp