]> git.ipfire.org Git - thirdparty/Python/cpython.git/commitdiff
asyncio: Fix getaddrinfo to accept service names (for port)
authorYury Selivanov <yselivanov@sprymix.com>
Thu, 2 Jun 2016 20:51:07 +0000 (16:51 -0400)
committerYury Selivanov <yselivanov@sprymix.com>
Thu, 2 Jun 2016 20:51:07 +0000 (16:51 -0400)
Patch by A. Jesse Jiryu Davis

Lib/asyncio/base_events.py
Lib/test/test_asyncio/test_base_events.py

index e5feb99857463dd18a7ff5f656a1c94e3fff028e..2b2c18536d7b0f9cb464c03516c62c23fe9bbf2d 100644 (file)
@@ -102,10 +102,26 @@ def _ipaddr_info(host, port, family, type, proto):
     else:
         return None
 
-    if port in {None, '', b''}:
+    if port is None:
         port = 0
-    elif isinstance(port, (bytes, str)):
-        port = int(port)
+    elif isinstance(port, bytes):
+        if port == b'':
+            port = 0
+        else:
+            try:
+                port = int(port)
+            except ValueError:
+                # Might be a service name like b"http".
+                port = socket.getservbyname(port.decode('ascii'))
+    elif isinstance(port, str):
+        if port == '':
+            port = 0
+        else:
+            try:
+                port = int(port)
+            except ValueError:
+                # Might be a service name like "http".
+                port = socket.getservbyname(port)
 
     if hasattr(socket, 'inet_pton'):
         if family == socket.AF_UNSPEC:
index 81c35c89c1379bd832115cdcead6578df6da21fd..e800ec4340011e96c4f11f28b45a97fe95780c17 100644 (file)
@@ -146,6 +146,26 @@ class BaseEventTests(test_utils.TestCase):
             (INET, STREAM, TCP, '', ('1.2.3.4', 1)),
             base_events._ipaddr_info('1.2.3.4', b'1', INET, STREAM, TCP))
 
+    def test_getaddrinfo_servname(self):
+        INET = socket.AF_INET
+        STREAM = socket.SOCK_STREAM
+        TCP = socket.IPPROTO_TCP
+
+        self.assertEqual(
+            (INET, STREAM, TCP, '', ('1.2.3.4', 80)),
+            base_events._ipaddr_info('1.2.3.4', 'http', INET, STREAM, TCP))
+
+        self.assertEqual(
+            (INET, STREAM, TCP, '', ('1.2.3.4', 80)),
+            base_events._ipaddr_info('1.2.3.4', b'http', INET, STREAM, TCP))
+
+        # Raises "service/proto not found".
+        with self.assertRaises(OSError):
+            base_events._ipaddr_info('1.2.3.4', 'nonsense', INET, STREAM, TCP)
+
+        with self.assertRaises(OSError):
+            base_events._ipaddr_info('1.2.3.4', 'nonsense', INET, STREAM, TCP)
+
     @patch_socket
     def test_ipaddr_info_no_inet_pton(self, m_socket):
         del m_socket.inet_pton