如何在python中创建IPv6套接字?为什么会出现socket.error:(22,'Invalid arguments')? [英] How to create IPv6 socket at python? Why got the socket.error: (22, 'Invalid argument')?

查看:390
本文介绍了如何在python中创建IPv6套接字?为什么会出现socket.error:(22,'Invalid arguments')?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to ceate Ipv6 socket at python, I do it like this:

#!/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') ?

有人可以帮助我吗?谢谢!

Can anyone help me? thanks!

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

I redo it like this, but still cannot work

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

You should use the sa.bind(sockaddr) where sockaddr is obtained from 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)

第二期

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

If you look at the example provided in the socket documentation at

套接字接受三个参数

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不同

And if you used getaddressinfo to get the values for proto then the value is different from the default 0

但是当我执行以下命令时,我得到一个不同的协议值-17. 您可能也想对此进行调查.

But when I executed the following, I get a different protocol value - 17. You may want to investigate this too.

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

And of course socket.has_ipv6 is True for me.

这篇关于如何在python中创建IPv6套接字?为什么会出现socket.error:(22,'Invalid arguments')?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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