如何根据目标地址发送消息之前确定源地址?

时间:2014-04-03 17:59:01

标签: python linux sockets networking udp

这有点难以解释,所以请耐心等待。

在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>它会告诉我src地址
https://stackoverflow.com/a/5557459/334632

我最终深入挖掘了iproute2源代码,但我看不到它的用途,我可以快捷方式。 https://git.kernel.org/cgit/linux/kernel/git/shemminger/iproute2.git/tree/ip/iproute.c#n1376

我最终可能只是创建一个子进程并解析结果,但我想尽可能避免这种情况。

1 个答案:

答案 0 :(得分:3)

如果您不关心Linux以外的任何内容,可以使用pyroute2模块。例如,要获取特定IP地址的路由信息​​:

>>> import pprint
>>> import pyroute2
>>> import socket
>>> ip = pyroute2.IPRoute()
>>> pprint.pprint(ip.get_routes(family=socket.AF_INET, dst='127.0.0.6'))
[{'attrs': [['RTA_TABLE', 254],
            ['RTA_DST', '127.0.0.6'],
            ['RTA_OIF', 1],
            ['RTA_PREFSRC', '127.0.0.1'],
            ['RTA_CACHEINFO',
             {'rta_clntref': 1,
              'rta_error': 0,
              'rta_expires': 0,
              'rta_id': 0,
              'rta_lastuse': 0,
              'rta_ts': 0,
              'rta_tsage': 0,
              'rta_used': 1}]],
  'dst_len': 32,
  'event': 'RTM_NEWROUTE',
  'family': 2,
  'flags': 2147484160,
  'proto': 0,
  'scope': 0,
  'src_len': 0,
  'table': 254,
  'tos': 0,
  'type': 2}]

不幸的是,这不适用于pypi上的pyroute2的最新版本;我必须从源代码安装才能获得这些结果。

相关问题