]> kaliko git repositories - python-musicpd.git/commitdiff
mpd.py: loop over addresses returned by getaddrinfo to connect to
authorJ. Alexander Treuman <jat@spatialrift.net>
Sun, 23 Mar 2008 20:47:06 +0000 (16:47 -0400)
committerJ. Alexander Treuman <jat@spatialrift.net>
Sun, 23 Mar 2008 20:47:06 +0000 (16:47 -0400)
This allows us to support IPv6 and multi-homed hostnames.  getaddrinfo is
called with the same flags as libmpdclient uses, making address resolution
consistent between the two.

mpd.py

diff --git a/mpd.py b/mpd.py
index ce1784b4227da5aa437801ef2d536b91d8cb4851..ae1f2b3c349a6360127ecd06f86451432d3f453d 100644 (file)
--- a/mpd.py
+++ b/mpd.py
@@ -289,8 +289,22 @@ class MPDClient(object):
     def connect(self, host, port):
         if self._sock:
             raise ConnectionError, "Already connected"
-        self._sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
-        self._sock.connect((host, port))
+        msg = "getaddrinfo returns an empty list"
+        for res in socket.getaddrinfo(host, port, socket.AF_UNSPEC,
+                                      socket.SOCK_STREAM, socket.IPPROTO_TCP,
+                                      socket.AI_ADDRCONFIG):
+            af, socktype, proto, canonname, sa = res
+            try:
+                self._sock = socket.socket(af, socktype, proto)
+                self._sock.connect(sa)
+            except socket.error, msg:
+                if self._sock:
+                    self._sock.close()
+                self._sock = None
+                continue
+            break
+        if not self._sock:
+            raise socket.error, msg
         self._rfile = self._sock.makefile("rb")
         self._wfile = self._sock.makefile("wb")
         self._hello()