python ipv6 linux,Python socket 模块,IPV6_V6ONLY 实例源码 - 编程字典

def bind_sockets(port, address=None, family=socket.AF_UNSPEC, backlog=128, flags=None):

"""Creates listening sockets bound to the given port and address.

Returns a list of socket objects (multiple sockets are returned if

the given address maps to multiple IP addresses, which is most common

for mixed IPv4 and IPv6 use).

Address may be either an IP address or hostname. If it's a hostname,

the server will listen on all IP addresses associated with the

name. Address may be an empty string or None to listen on all

available interfaces. Family may be set to either `socket.AF_INET`

or `socket.AF_INET6` to restrict to IPv4 or IPv6 addresses, otherwise

both will be used if available.

The ``backlog`` argument has the same meaning as for

`socket.listen() `.

``flags`` is a bitmask of AI_* flags to `~socket.getaddrinfo`, like

``socket.AI_PASSIVE | socket.AI_NUMERICHOST``.

"""

sockets = []

if address == "":

address = None

if not socket.has_ipv6 and family == socket.AF_UNSPEC:

# Python can be compiled with --disable-ipv6, which causes

# operations on AF_INET6 sockets to fail, but does not

# automatically exclude those results from getaddrinfo

# results.

# http://bugs.python.org/issue16208

family = socket.AF_INET

if flags is None:

flags = socket.AI_PASSIVE

for res in set(socket.getaddrinfo(address, port, family, socket.SOCK_STREAM,

0, flags)):

af, socktype, proto, canonname, sockaddr = res

try:

sock = socket.socket(af, socktype, proto)

except socket.error as e:

if e.args[0] == errno.EAFNOSUPPORT:

continue

raise

set_close_exec(sock.fileno())

if os.name != 'nt':

sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

if af == socket.AF_INET6:

# On linux, ipv6 sockets accept ipv4 too by default,

# but this makes it impossible to bind to both

# 0.0.0.0 in ipv4 and :: in ipv6. On other systems,

# separate sockets *must* be used to listen for both ipv4

# and ipv6. For consistency, always disable ipv4 on our

# ipv6 sockets and use a separate ipv4 socket when needed.

#

# Python 2.x on windows doesn't have IPPROTO_IPV6.

if hasattr(socket, "IPPROTO_IPV6"):

sock.setsockopt(socket.IPPROTO_IPV6, socket.IPV6_V6ONLY, 1)

sock.setblocking(0)

sock.bind(sockaddr)

sock.listen(backlog)

sockets.append(sock)

return sockets

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值