本文整理汇总了Python中socket.SO_REUSEPORT属性的典型用法代码示例。如果您正苦于以下问题:Python socket.SO_REUSEPORT属性的具体用法?Python socket.SO_REUSEPORT怎么用?Python socket.SO_REUSEPORT使用的例子?那么恭喜您, 这里精选的属性代码示例或许可以为您提供帮助。您也可以进一步了解该属性所在类socket
的用法示例。
在下文中一共展示了socket.SO_REUSEPORT属性的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: reserve_sock_addr
# 需要导入模块: import socket [as 别名]
# 或者: from socket import SO_REUSEPORT [as 别名]
def reserve_sock_addr() -> Iterator[Tuple[str, int]]:
"""Reserve an available TCP port to listen on.
The reservation is done by binding a TCP socket to port 0 with
``SO_REUSEPORT`` flag set (requires Linux >=3.9). The socket is
then kept open until the generator is closed.
To reduce probability of 'hijacking' port, socket should stay open
and should be closed _just before_ starting of ``tf.train.Server``
"""
so_reuseport = get_so_reuseport()
if so_reuseport is None:
raise RuntimeError(
"SO_REUSEPORT is not supported by the operating system") from None
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
sock.setsockopt(socket.SOL_SOCKET, so_reuseport, 1)
sock.bind(("", 0))
_ipaddr, port = sock.getsockname()
yield (socket.getfqdn(), port)
示例2: receive
# 需要导入模块: import socket [as 别名]
# 或者: from socket import SO_REUSEPORT [as 别名]
def receive(*, group=DEFAULT_GROUP, port=DEFAULT_PORT, timeout=None):
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
try:
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
try:
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1)
except AttributeError:
# not available on Windows
pass
s.bind(('', port))
s.settimeout(timeout)
mreq = struct.pack('4sl', socket.inet_aton(group), socket.INADDR_ANY)
s.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, mreq)
try:
data, sender_addr = s.recvfrom(4096)
finally:
s.setsockopt(socket.IPPROTO_IP, socket.IP_DROP_MEMBERSHIP, mreq)
finally:
s.close()
return data, sender_addr
示例3: __init__
# 需要导入模块: import socket [as 别名]
# 或者: from socket import SO_REUSEPORT [as 别名]
def __init__(self, summary_table, group=DEFAULT_GROUP, port=DEFAULT_PORT, timeout=None):
self._dummy_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
self._socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
try:
self._socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
try:
self._socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1)
except AttributeError:
# not available on Windows
pass
self._socket.bind(('', port))
self._socket.settimeout(timeout)
self._mreq = struct.pack('4sl', socket.inet_aton(group), socket.INADDR_ANY)
self._socket.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, self._mreq)
except Exception:
self._dummy_socket.close()
self._socket.close()
raise
self._is_shutdown = False
self._summary_table = summary_table
self._group = group
self._port = port
示例4: tcp_server_socket
# 需要导入模块: import socket [as 别名]
# 或者: from socket import SO_REUSEPORT [as 别名]
def tcp_server_socket(host, port, family=socket.AF_INET, backlog=100,
reuse_address=True, reuse_port=False, ssl_context=None):
raw_socket = socket.socket(family, socket.SOCK_STREAM)
try:
if reuse_address:
raw_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, True)
if reuse_port:
try:
raw_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, True)
except (AttributeError, OSError) as e:
log.warning('reuse_port=True option failed', exc_info=True)
raw_socket.bind((host, port))
raw_socket.listen(backlog)
except Exception:
raw_socket.close()
raise
return raw_socket
示例5: accept
# 需要导入模块: import socket [as 别名]
# 或者: from socket import SO_REUSEPORT [as 别名]
def accept(port):
logger.info("accept %s", port)
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1)
s.bind(('', port))
s.listen(1)
s.settimeout(5)
while not STOP.is_set():
try:
conn, addr = s.accept()
except socket.timeout:
continue
else:
logger.info("Accept %s connected!", port)
# STOP.set()
示例6: connect
# 需要导入模块: import socket [as 别名]
# 或者: from socket import SO_REUSEPORT [as 别名]
def connect(local_addr, addr):
logger.info("connect from %s to %s", local_addr, addr)
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1)
s.bind(local_addr)
while not STOP.is_set():
try:
s.connect(addr)
except socket.error:
continue
# except Exception as exc:
# logger.exception("unexpected exception encountered")
# break
else:
logger.info("connected from %s to %s success!", local_addr, addr)
# STOP.set()
示例7: test_create_server_reuse_port
# 需要导入模块: import socket [as 别名]
# 或者: from socket import SO_REUSEPORT [as 别名]
def test_create_server_reuse_port(self):
proto = MyProto(self.loop)
f = self.loop.create_server(
lambda: proto, '0.0.0.0', 0)
server = self.loop.run_until_complete(f)
self.assertEqual(len(server.sockets), 1)
sock = server.sockets[0]
self.assertFalse(
sock.getsockopt(
socket.SOL_SOCKET, socket.SO_REUSEPORT))
server.close()
test_utils.run_briefly(self.loop)
proto = MyProto(self.loop)
f = self.loop.create_server(
lambda: proto, '0.0.0.0', 0, reuse_port=True)
server = self.loop.run_until_complete(f)
self.assertEqual(len(server.sockets), 1)
sock = server.sockets[0]
self.assertTrue(
sock.getsockopt(
socket.SOL_SOCKET, socket.SO_REUSEPORT))
server.close()
示例8: check_udp_connectivity
# 需要导入模块: import socket [as 别名]
# 或者: from socket import SO_REUSEPORT [as 别名]
def check_udp_connectivity(url, timeout=None):
"""Check UDP connectivity."""
ipaddr, port = url.rsplit(':', 1)
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
sock.settimeout(timeout)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1)
sock.bind(('', int(port)))
mreq = struct.pack("4sl", socket.inet_aton(ipaddr), socket.INADDR_ANY)
sock.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, mreq)
try:
if sock.recv(10240):
return True
except socket.timeout:
pass
return False
示例9: bind_port
# 需要导入模块: import socket [as 别名]
# 或者: from socket import SO_REUSEPORT [as 别名]
def bind_port(sock, host="localhost"):
if sock.family == socket.AF_INET and sock.type == socket.SOCK_STREAM:
if hasattr(socket, 'SO_REUSEADDR'):
if sock.getsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR) == 1:
raise ValueError("tests should never set the SO_REUSEADDR "
"socket option on TCP/IP sockets!")
if hasattr(socket, 'SO_REUSEPORT'):
try:
if sock.getsockopt(socket.SOL_SOCKET,
socket.SO_REUSEPORT) == 1:
raise ValueError(
"tests should never set the SO_REUSEPORT "
"socket option on TCP/IP sockets!")
except OSError:
# Python's socket module was compiled using modern headers
# thus defining SO_REUSEPORT but this process is running
# under an older kernel that does not support SO_REUSEPORT.
pass
if hasattr(socket, 'SO_EXCLUSIVEADDRUSE'):
sock.setsockopt(socket.SOL_SOCKET, socket.SO_EXCLUSIVEADDRUSE, 1)
sock.bind((host, 0))
port = sock.getsockname()[1]
return port
示例10: _server
# 需要导入模块: import socket [as 别名]
# 或者: from socket import SO_REUSEPORT [as 别名]
def _server(self) -> None:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
try:
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1)
except AttributeError:
pass
# set the timeout to prevent the server loop from
# blocking indefinitaly on sock.accept()
sock.settimeout(0.5)
sock.bind((self._host, self._port))
sock.listen(1)
with sock:
while not self._closing.is_set():
try:
client, addr = sock.accept()
with client:
sout = client.makefile('w', encoding='utf-8')
sin = client.makefile('r', encoding='utf-8')
self._interactive_loop(sin, sout)
except (socket.timeout, OSError):
continue
示例11: __init__
# 需要导入模块: import socket [as 别名]
# 或者: from socket import SO_REUSEPORT [as 别名]
def __init__(self, hostname, port,
invoke=None, target=None, max_clients=5):
"""
:param hostname: Hostname on which to listen, '' to accept any origin
:param port: The TCP port to listen on
:param invoke: The method to call at a new client connection
:param target: The object to expose, will fallback to self if None
:param max_clients: The max number of concurrent connection
"""
s, pathspec = _get_socket(hostname, port, unlink=True)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1)
s.bind(pathspec)
self.server_socket = s
s.listen(max_clients)
self.invoke = invoke
self.target = target
self.client_count = 0
示例12: __init__
# 需要导入模块: import socket [as 别名]
# 或者: from socket import SO_REUSEPORT [as 别名]
def __init__(self, own_id, is_client=True):
self.address = get_ownip()
self.broadcast = '255.255.255.255'
self.port = settings.discovery_port
self.own_id = own_id
self.mask = IS_CLIENT if is_client else IS_SERVER
# Create UDP socket
self.handle = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
# Ask operating system to let us do broadcasts from socket
self.handle.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
if hasattr(socket, 'SO_REUSEPORT'):
self.handle.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1)
else:
self.handle.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
# Bind UDP socket to local port so we can receive pings
self.handle.bind(('', self.port))
示例13: start
# 需要导入模块: import socket [as 别名]
# 或者: from socket import SO_REUSEPORT [as 别名]
def start(self):
"""Start the discovery process and listen for discovery requests."""
self._logger.debug("Starting servers discovery")
# Create a datagram socket bound on port 31013
self._socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
self._socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
if platform.system() == "Darwin":
self._socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1)
self._socket.bind(("", 31013))
self._socket.settimeout(0)
self._socket.setblocking(0)
self._read_notifier = QSocketNotifier(
self._socket.fileno(), QSocketNotifier.Read, self
)
self._read_notifier.activated.connect(self._notify_read)
self._read_notifier.setEnabled(True)
self._started = True
示例14: test_create_datagram_endpoint_ip_addr
# 需要导入模块: import socket [as 别名]
# 或者: from socket import SO_REUSEPORT [as 别名]
def test_create_datagram_endpoint_ip_addr(self, m_socket):
def getaddrinfo(*args, **kw):
self.fail('should not have called getaddrinfo')
m_socket.getaddrinfo = getaddrinfo
m_socket.socket.return_value.bind = bind = mock.Mock()
self.loop._add_reader = mock.Mock()
self.loop._add_reader._is_coroutine = False
reuseport_supported = hasattr(socket, 'SO_REUSEPORT')
coro = self.loop.create_datagram_endpoint(
lambda: MyDatagramProto(loop=self.loop),
local_addr=('1.2.3.4', 0),
reuse_address=False,
reuse_port=reuseport_supported)
t, p = self.loop.run_until_complete(coro)
try:
bind.assert_called_with(('1.2.3.4', 0))
m_socket.socket.assert_called_with(family=m_socket.AF_INET,
proto=m_socket.IPPROTO_UDP,
type=m_socket.SOCK_DGRAM)
finally:
t.close()
test_utils.run_briefly(self.loop) # allow transport to close
示例15: create_sockets
# 需要导入模块: import socket [as 别名]
# 或者: from socket import SO_REUSEPORT [as 别名]
def create_sockets(mcst_ipaddr, mcst_port):
mreq = struct.pack("4sl", socket.inet_aton(mcst_ipaddr),
socket.INADDR_ANY)
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM,
socket.IPPROTO_UDP)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, mreq)
if platform.system() == "Windows":
s.bind(("", mcst_port))
return (s, )
else:
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1)
s.bind((mcst_ipaddr, mcst_port))
bsock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM,
socket.IPPROTO_UDP)
bsock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
bsock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1)
bsock.bind(("", 1901))
return (s, bsock)