为什么%en0后缀无法在Python中连接本地链接的IPv6 TCP套接字? [英] Why doesn't a %en0 suffix work to connect a link-local IPv6 TCP socket in Python?

查看:90
本文介绍了为什么%en0后缀无法在Python中连接本地链接的IPv6 TCP套接字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大约一周前,StackOverflow上的某人为什么他们的用于连接到IPv6链接本地地址的Python代码无法正常工作,我回答说,由于它是链接本地地址,因此他们需要添加%en0(或所需的本地接口名称)后缀到他们的目标IP地址.我以为我知道我在说什么,所以我在回答之前并没有真正测试过我的建议(可耻!).

A week or so ago someone on StackOverflow asked why their Python code for connecting to an IPv6 link-local address wasn't working, and I replied that since it was a link-local address they needed to add a %en0 (or whatever the desired local-interface-name is) suffix to their target IP address. I thought I knew what I was talking about, so I didn't actually test my suggestion before answering (shame on me!).

今天我去为自己使用了同样的技术,只是发现它似乎不起作用. :^(也就是说,此代码不起作用:

Today I went to use that same technique for myself, only to find that it doesn't seem to work. :^( That is, this code does not work:

>>> from socket import *
>>> s = socket(AF_INET6, SOCK_STREAM)
>>> s.connect(('fe80::21f:5bff:fe3f:1b36%en0', 2001))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<string>", line 1, in connect
socket.error: [Errno 65] No route to host

另一方面,下面的代码可以正常工作(带或不带%en0后缀):

The following code, on the other hand, DOES work (with or without the %en0 suffix):

>>> from socket import *
>>> s = socket(AF_INET6, SOCK_STREAM)
>>> s.connect(('fe80::21f:5bff:fe3f:1b36%en0', 2001, 0, 6))
>>> 

...但是我不喜欢那样做,因为为了弄清楚要为最后一个参数提供哪个作用域ID整数,我必须执行一堆不是很便携的代码来进行迭代在本地接口列表中,找到名为"en0"的接口,并提取其作用域ID,这比我想要的要复杂得多.

... but I don't like doing it that way, because in order to figure out which scope ID integer to supply for the last argument, I have to execute a bunch of not-very-portable code to iterate over the local interfaces list, find the interface named 'en0', and extract its scope ID, which is more complexity overhead than I'd like to have.

鉴于connect()正在接受IP地址的%en0后缀,为什么它不按预期实际使用它来确定作用域ID?

Given that connect() is accepting the %en0 suffix to the IP address, why isn't it actually using it as expected to determine the scope ID?

FWIW,我正在MacOS/X 10.6.4下使用Python 2.6.1进行测试.

FWIW, I am testing with Python 2.6.1 under MacOS/X 10.6.4.

推荐答案

这是建立ipv6连接的正确方法:

This is the correct way to do an ipv6 connection:

>>> addrinfo = getaddrinfo('fe80::225:ff:fecd:5aa0%en0', 2001, AF_INET6, SOCK_STREAM)
>>> addrinfo
[(30, 1, 6, '', ('fe80::225:ff:fecd:5aa0%en0', 2001, 0, 4))]
>>> (family, socktype, proto, canonname, sockaddr) = addrinfo[0]
>>> s = socket(family, socktype, proto)
>>> s.connect(sockaddr)

getaddrinfo()将为您返回正确的数字范围和流信息.

getaddrinfo() will return the correct numerical scope and flow information for you.

这篇关于为什么%en0后缀无法在Python中连接本地链接的IPv6 TCP套接字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆