net: avoid TCP self-connect

Fixes #2690.

R=golang-dev, bradfitz
CC=golang-dev
https://golang.org/cl/5650071
diff --git a/src/pkg/net/dial_test.go b/src/pkg/net/dial_test.go
index f130a11..9196450 100644
--- a/src/pkg/net/dial_test.go
+++ b/src/pkg/net/dial_test.go
@@ -84,3 +84,34 @@
 		}
 	}
 }
+
+func TestSelfConnect(t *testing.T) {
+	// Test that Dial does not honor self-connects.
+	// See the comment in DialTCP.
+
+	// Find a port that would be used as a local address.
+	l, err := Listen("tcp", "127.0.0.1:0")
+	if err != nil {
+		t.Fatal(err)
+	}
+	c, err := Dial("tcp", l.Addr().String())
+	if err != nil {
+		t.Fatal(err)
+	}
+	addr := c.LocalAddr().String()
+	c.Close()
+	l.Close()
+
+	// Try to connect to that address repeatedly.
+	n := 100000
+	if testing.Short() {
+		n = 1000
+	}
+	for i := 0; i < n; i++ {
+		c, err := Dial("tcp", addr)
+		if err == nil {
+			c.Close()
+			t.Errorf("#%d: Dial %q succeeded", i, addr)
+		}
+	}
+}