Search code examples
gotcp

How to listen to 0.0.0.0:8080 with ListenTCP


How can I listen on TCP port 8080 with net.ListenTCP ?

With net.Conn I simply do this:

ln, err := net.Listen("tcp", ":8080")

Whats the simplest solution for ListenTCP?


Solution

  • To use net.ListenTCP, you must construct a net.TCPAddr struct. The simplest way is to resolve one from the same string you pass to Dial or Listen:

    addr, err := net.ResolveTCPAddr("tcp", ":8000")
    if err != nil {
        panic(err)
    }
    
    ln, err := net.ListenTCP("tcp", addr)
    

    Per the comments on net.ResolveTCPAddr, valid combinations of "network" and "address" can be found in the net.Dial documentation.