如何在python中创建IPv6套接字?为什么会出现socket.error:(22,'Invalid arguments')?


问题内容

我想在python上创建Ipv6套接字,我这样做是这样的:

#!/usr/bin/env python
import sys
import struct
import socket

host = 'fe80::225:b3ff:fe26:576'
sa = socket.socket(socket.AF_INET6, socket.SOCK_DGRAM)
sa.bind((host , 50000))

但是失败了:

socket.error: (22, 'Invalid argument') ?

谁能帮我?谢谢!

我像这样重做,但仍然无法正常工作

    >>>host = 'fe80::225:b3ff:fe26:576'
    >>>sa = socket.socket(socket.AF_INET6, socket.SOCK_DGRAM)
    >>>res = socket.getaddrinfo(host, port, socket.AF_UNSPEC, socket.SOCK_DGRAM, 0, socket.AI_PASSIVE)
    >>>family, socktype, proto, canonname, sockaddr = res[0]
    >>>print sockaddr
('fe80::225:b3ff:fe26:576', 50001, 0, 0)
    >>>sa.bind(sockaddr)
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
  File "<string>", line 1, in bind
socket.error: (22, 'Invalid argument')

问题答案:

这个问题有两个部分

首要问题

您应该使用sa.bind(sockaddr),其中从getaddrinfo获得sockaddr

>>> HOST = 'localhost'
>>> PORT = 50007 
>>> res = socket.getaddrinfo(HOST, PORT, socket.AF_UNSPEC, socket.SOCK_DGRAM, 0, socket.AI_PASSIVE)
>>> family, socktype, proto, canonname, sockaddr = res[1]
>>> proto
17
>>> sockaddr
('fe80::1%lo0', 50007, 0, 1)

第二期

如果您查看套接字文档中提供的示例,请访问

套接字接受三个参数

socket( [family[, type[, proto]]])

根据文档

Create a new socket using the given address family, 
socket type and protocol number. The address family 
should be AF_INET (the default), AF_INET6 or AF_UNIX. 
The socket type should be SOCK_STREAM (the default), 
SOCK_DGRAM or perhaps one of the other "SOCK_" constants. 
The protocol number is usually zero and may be omitted in that case.

而且,如果您使用getaddressinfo获取proto的值,则该值不同于默认值0

但是,当我执行以下命令时,会得到一个不同的协议值-17。

当然,socket.has_ipv6对我来说是正确的。