Skip to content

Commit 4f06028

Browse files
committed
fix: use dual-stack socket instead of IPv4-only
By using an INET6 socket with IPV6_V6ONLY disabled, legacy IPv4 can still be reached. To connect to v4 IPs, the addresses are mapped to IPv6. IPv6 addresses are only used when a hostname resolves to one and the system has a non-local IPv6 available. For hosts with IPv6 completely disabled for some reason, the socket falls back to v4-only.
1 parent b2e3c9d commit 4f06028

File tree

1 file changed

+17
-2
lines changed

1 file changed

+17
-2
lines changed

pychromecast/socket_client.py

Lines changed: 17 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -360,7 +360,16 @@ def mdns_backoff(
360360
self.host,
361361
self.port,
362362
)
363-
self.socket.connect((self.host, self.port))
363+
364+
mapped_host = socket.getaddrinfo(
365+
self.host,
366+
self.port,
367+
self.socket.family,
368+
socket.SOCK_STREAM,
369+
flags=(socket.AI_ADDRCONFIG | socket.AI_V4MAPPED),
370+
)[0][4]
371+
372+
self.socket.connect(mapped_host)
364373
context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
365374
context.check_hostname = False
366375
context.verify_mode = ssl.CERT_NONE
@@ -1133,7 +1142,13 @@ def new_socket() -> socket.socket:
11331142
Try to set SO_REUSEPORT for BSD-flavored systems if it's an option.
11341143
Catches errors if not.
11351144
"""
1136-
new_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
1145+
try:
1146+
new_sock = socket.socket(socket.AF_INET6, socket.SOCK_STREAM)
1147+
new_sock.setsockopt(socket.IPPROTO_IPV6, socket.IPV6_V6ONLY, 0) # ensuring dual-stack
1148+
except OSError:
1149+
# falling back to IPv4 on systems without IPv6
1150+
new_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
1151+
11371152
new_sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
11381153

11391154
try:

0 commit comments

Comments
 (0)