]> Sergey Matveev's repositories - btrtrc.git/commitdiff
Tidy up the listen function
authorMatt Joiner <anacrolix@gmail.com>
Tue, 24 May 2016 09:45:42 +0000 (19:45 +1000)
committerMatt Joiner <anacrolix@gmail.com>
Tue, 24 May 2016 09:45:42 +0000 (19:45 +1000)
client.go

index f77fafee487ea6d0e93032a4e6b195ad70e12c1d..340c7317c4d0769820a6fa18e1dae810a39eaedb 100644 (file)
--- a/client.go
+++ b/client.go
@@ -212,6 +212,7 @@ func listenBothSameDynamicPort(networkSuffix, host string) (tcpL net.Listener, u
        }
 }
 
+// Listen to enabled protocols, ensuring ports match.
 func listen(tcp, utp bool, networkSuffix, addr string) (tcpL net.Listener, utpSock *utp.Socket, listenedAddr string, err error) {
        if addr == "" {
                addr = ":50007"
@@ -221,20 +222,29 @@ func listen(tcp, utp bool, networkSuffix, addr string) (tcpL net.Listener, utpSo
                return
        }
        if tcp && utp && port == 0 {
+               // If both protocols are active, they need to have the same port.
                return listenBothSameDynamicPort(networkSuffix, host)
        }
+       defer func() {
+               if err != nil {
+                       listenedAddr = ""
+               }
+       }()
        if tcp {
                tcpL, err = listenTCP(networkSuffix, addr)
                if err != nil {
                        return
                }
+               defer func() {
+                       if err != nil {
+                               tcpL.Close()
+                       }
+               }()
                listenedAddr = tcpL.Addr().String()
-
        }
        if utp {
                utpSock, err = listenUTP(networkSuffix, addr)
-               if err != nil && tcp {
-                       tcpL.Close()
+               if err != nil {
                        return
                }
                listenedAddr = utpSock.Addr().String()