Search code examples
gonetwork-programmingtcp

How to know which connection closed in "use of closed network connection" error


I'm proxying TCP connections in Go using io.Copy

_, err := io.Copy(src, dst)
if err != nil {
   log.Println(err)
}

and one connection closes therefore sending this error:

readfrom tcp 171.31.80.49:10000->88.39.116.204:56210: use of closed network connection

How do I know which network connection closed? i.e. 171.31.80.49:10000 or 88.39.116.204:56210.


Solution

  • A TCP connection is a pair of IP and port pairs. In your case, the connection is 171.31.80.49:10000->88.39.116.204:56210. It is the connection, and it is closed. There is no connection 171.31.80.49:10000 or 88.39.116.204:56210.

    There are two connections in your example: src and dst (you misnamed them, by the way: https://pkg.go.dev/io#Copy). If your question is which connection is getting closed, then, according to the error message, it's dst (which is supposed to be named src).

    Why? Because the message says: readfrom ..., the error occurs when the io.Copy is reading from the Reader, which in our case is dst.