diff --git a/Lib/socket.py b/Lib/socket.py index 21a852155abb3b3..002df2e05e1f989 100644 --- a/Lib/socket.py +++ b/Lib/socket.py @@ -832,7 +832,7 @@ def getfqdn(name=''): """ name = name.strip() if not name or name in ('0.0.0.0', '::'): - name = gethostname() + return gethostname() try: hostname, aliases, ipaddrs = gethostbyaddr(name) except error: diff --git a/Lib/test/test_socket.py b/Lib/test/test_socket.py index e4b3d848923f8c9..f8c4b6f6c266df8 100644 --- a/Lib/test/test_socket.py +++ b/Lib/test/test_socket.py @@ -1187,6 +1187,17 @@ def test_sethostname(self): finally: socket.sethostname(oldhn) + def test_getfqdn_undefined_address(self): + for addr in ('', '0.0.0.0', '::'): + with self.subTest(addr=addr): + called = [] + with mock.patch.object( + socket, 'gethostbyaddr', + side_effect=lambda addr: called.append(addr) or ("", [], []) + ): + socket.getfqdn(addr) + self.assertFalse(called, f"gethostbyaddr was called for undefined address {addr!r}") + @unittest.skipUnless(hasattr(socket, 'if_nameindex'), 'socket.if_nameindex() not available.') @support.skip_android_selinux('if_nameindex') diff --git a/Misc/ACKS b/Misc/ACKS index 4a3f6482294e087..c79f5e3447f66c3 100644 --- a/Misc/ACKS +++ b/Misc/ACKS @@ -1877,6 +1877,7 @@ Daniel Stutzbach Andreas Stührk Colin Su Pal Subbiah +Ilari Suhonen Michael J. Sullivan Nathan Sullivan Mark Summerfield diff --git a/Misc/NEWS.d/next/Core_and_Builtins/2026-09-06-21-40-17.gh-issue-106505.nwL_5c.rst b/Misc/NEWS.d/next/Core_and_Builtins/2026-09-06-21-40-17.gh-issue-106505.nwL_5c.rst new file mode 100644 index 000000000000000..894263a72702d87 --- /dev/null +++ b/Misc/NEWS.d/next/Core_and_Builtins/2026-09-06-21-40-17.gh-issue-106505.nwL_5c.rst @@ -0,0 +1,2 @@ +Fix ``getfqdn()`` attempting to resolve the computer's own hostname, instead +of returning it as-is.