]> kaliko git repositories - python-musicpd.git/blobdiff - mpd.py
mpd.py: strip trailing \n from MPD's hello line for a nicer error message
[python-musicpd.git] / mpd.py
diff --git a/mpd.py b/mpd.py
index 33449ca5aabbe8abb3f974354bebabe48f8a44fb..c924b3c758940ba4a1d4d43014339dc34e92cce7 100644 (file)
--- a/mpd.py
+++ b/mpd.py
@@ -275,6 +275,7 @@ class MPDClient(object):
         line = self._rfile.readline()
         if not line.endswith("\n"):
             raise ConnectionError, "Connection lost while reading MPD hello"
+        line = line.rstrip("\n")
         if not line.startswith(HELLO_PREFIX):
             raise ProtocolError, "Got invalid MPD hello: '%s'" % line
         self.mpd_version = line[len(HELLO_PREFIX):].strip()
@@ -288,12 +289,30 @@ class MPDClient(object):
 
     def connect(self, host, port):
         if self._sock:
-            self.disconnect()
-        self._sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
-        self._sock.connect((host, port))
+            raise ConnectionError, "Already connected"
+        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()
+        try:
+            self._hello()
+        except (socket.error, MPDError):
+            self.disconnect()
+            raise
 
     def disconnect(self):
         self._rfile.close()