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

2023-11-23

我想在 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) ,其中 sockaddr 是从 getaddrinfo 获取的

>>> 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)

第二期

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

  • http://docs.python.org/release/2.5.2/lib/module-socket.html

套接字接受三个参数

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 对我来说是 True 。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

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

随机推荐