Merge pull request #3714 from sethb157/ipv6_only

Add support for IPv6-only environments
This commit is contained in:
Maximilian Hils 2019-11-19 18:32:29 +01:00 committed by GitHub
commit b9f3a310a7
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
1 changed files with 15 additions and 3 deletions

View File

@ -558,7 +558,7 @@ class TCPServer:
self.socket = None self.socket = None
try: try:
# First try to bind an IPv6 socket, with possible IPv4 if the OS supports it. # First try to bind an IPv6 socket, attempting to enable IPv4 support if the OS supports it.
# This allows us to accept connections for ::1 and 127.0.0.1 on the same socket. # This allows us to accept connections for ::1 and 127.0.0.1 on the same socket.
# Only works if self.address == "" # Only works if self.address == ""
self.socket = socket.socket(socket.AF_INET6, socket.SOCK_STREAM) self.socket = socket.socket(socket.AF_INET6, socket.SOCK_STREAM)
@ -572,8 +572,20 @@ class TCPServer:
self.socket = None self.socket = None
if not self.socket: if not self.socket:
# Binding to an IPv6 socket failed, lets fall back to IPv4. try:
self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # Binding to an IPv6 + IPv4 socket failed, lets fall back to IPv4 only.
self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)
self.socket.bind(self.address)
except socket.error:
if self.socket:
self.socket.close()
self.socket = None
if not self.socket:
# Binding to an IPv4 only socket failed, lets fall back to IPv6 only.
self.socket = socket.socket(socket.AF_INET6, socket.SOCK_STREAM)
self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1) self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)
self.socket.bind(self.address) self.socket.bind(self.address)