Skip to content

Commit 4529903

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 33d7770 commit 4529903

File tree

1 file changed

+16
-2
lines changed

1 file changed

+16
-2
lines changed

pychromecast/socket_client.py

Lines changed: 16 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -352,7 +352,16 @@ def mdns_backoff(
352352
self.host,
353353
self.port,
354354
)
355-
self.socket.connect((self.host, self.port))
355+
356+
mapped_host = socket.getaddrinfo(
357+
self.host,
358+
self.port,
359+
self.socket.family,
360+
socket.SOCK_STREAM,
361+
flags=(socket.AI_ADDRCONFIG | socket.AI_V4MAPPED),
362+
)[0][4]
363+
364+
self.socket.connect(mapped_host)
356365
context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
357366
context.check_hostname = False
358367
context.verify_mode = ssl.CERT_NONE
@@ -1135,7 +1144,12 @@ def new_socket() -> socket.socket:
11351144
Try to set SO_REUSEPORT for BSD-flavored systems if it's an option.
11361145
Catches errors if not.
11371146
"""
1138-
new_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
1147+
try:
1148+
new_sock = socket.socket(socket.AF_INET6, socket.SOCK_STREAM)
1149+
new_sock.setsockopt(socket.IPPROTO_IPV6, socket.IPV6_V6ONLY, 0)
1150+
except OSError:
1151+
new_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
1152+
11391153
new_sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
11401154

11411155
try:

0 commit comments

Comments
 (0)