I would like to initiate TCP connections between a process and other processes which are already listening from incoming TCP connections. I would like to use the same source address (ip-port) for these connections. I am programming in Go.
I tried to run this code, but the second DialTCP call fails.
func main() {
ourAddr, _ := net.ResolveTCPAddr("tcp", "localhost:51234")
otherAddr1, _ := net.ResolveTCPAddr("tcp", "localhost:51236")
otherAddr2, _ := net.ResolveTCPAddr("tcp", "localhost:51237")
conn1, err1 := net.DialTCP("tcp", ourAddr, otherAddr1)
if err1 != nil {
log.Fatal("err1: " + err1.Error())
}
defer conn1.Close()
conn2, err2 := net.DialTCP("tcp", ourAddr, otherAddr2) // <- this fails
if err2 != nil {
log.Fatal("err2: " + err2.Error())
}
defer conn2.Close()
}
The error message is: err2: dial tcp 127.0.0.1:51234->127.0.0.1:51237: bind: address already in use
(the problem should not be related to the destination processes since two instances of netcat are already listening on the destination addresses)
I also tried using other ports (in case they were still in use) and it failed the same way
Here is my go version:
go version go1.13.4 linux/amd64
It seems to me the problem is not related to TCP but to the way I am using the Go library. What am I doing wrong, and how am I supposed to do?