gpt4 book ai didi

sockets - 同时使用 INADDR_ANY 和特定 IP 绑定(bind)到同一端口

转载 作者:行者123 更新时间:2023-12-02 16:00:37 27 4
gpt4 key购买 nike

Python 中的一个简单实验(在 Windows 上)表明我能够同时绑定(bind)到通配符地址和特定地址上的同一端口:

import socket
import select

MY_PORT = 13337

sany = socket.socket()
sany.bind(('', MY_PORT))
sany.listen(0)

sloc = socket.socket()
sloc.bind(('127.0.0.1', MY_PORT))
sloc.listen(0)

socks = [sany, sloc]
ready, _, _ = select.select(socks, [], [])
print socks.index(ready[0])

从概念上讲,它们在应该涵盖的内容上是重叠的。通过从不同的提示符连接到 ('127.0.0.1', 13337) 继续实验表明更具体的套接字“wins”(即打印 1)。我在 SOCK_DGRAM 套接字中看到类似的行为。

我的问题如下:

  • 此行为是否具有某种契约性(Winsock、Berkeley Sockets 等)?
  • 这对于多播套接字应该如何表现?
  • 这在 *nix 系统上应该如何表现?

最佳答案

您所描述的内容在 Windows Server 2003 及更高版本上是可能的,但前提是两个 bind() 调用由同一用户帐户进行:

Using SO_REUSEADDR and SO_EXCLUSIVEADDRUSE

Enhanced socket security was added with the release of Windows Server 2003. In previous Microsoft server operating system releases, the default socket security easily allowed processes to hijack ports from unsuspecting applications. In Windows Server 2003, sockets are not in a sharable state by default. Therefore, if an application wants to allow other processes to reuse a port on which a socket is already bound, it must specifically enable it. If that is the case, the first socket to call bind on the port must have SO_REUSEADDR set on the socket. The only exception to this case occurs when the second bind call is performed by the same user account that made the original call to bind. This exception exists solely to provide backward compatibility.

The table below describes the behavior that occurs in Windows Server 2003 and later operating systems when a second socket attempts to bind to an address previously bound to by a first socket using specific socket options.

table

...

The socket binding behavior changes when the socket bind calls are made under different user accounts. The table below specifies the behavior that occurs in Windows Server 2003 and later operating systems when a second socket attempts to bind to an address previously bound to by a first socket using specific socket options and a different user account.

table

在早期的 Windows 版本中,行为有所不同:

The table below describes the behavior that occurs in Windows XP and earlier when a second socket attempts to bind to an address previously bound to by a first socket using specific socket options.

table

...

In the case where the first call to bind sets either SO_REUSEADDR or no socket options at all, the second bind call will "hijack" the port and the application will be unable to determine which of the two sockets received specific packets sent to the "shared" port.

关于sockets - 同时使用 INADDR_ANY 和特定 IP 绑定(bind)到同一端口,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33618949/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com