Moshe Marciano
Moshe Marciano

Reputation: 2337

Get IPv4 address from net tcp connection

I am trying to print out a log when a new TCP client connects to my Go server.

        l, err := net.Listen("tcp", bindPort)
        c, err := l.Accept()
        clientIP := c.RemoteAddr().String()
        fmt.Println("==> accepted new client, IP:", clientIP)

outputs from my testing on localhost

==> accepted new client, IP: [::1]:56780

I didn't find any way to get or convert it to an IPv4 (192.168.1.31) form.

Upvotes: 0

Views: 1128

Answers (1)

Fahim Bagar
Fahim Bagar

Reputation: 828

If you want to use IPv4, you may force it to listen to IPv4 only

bindPort := "0.0.0.0:1234"
// or to be more specific, bindPort := "192.168.1.31:1234"
l, err := net.Listen("tcp", bindPort)

I assume you run golang on Linux, IPv6 is more like a default listener if you use default kernel options.

And also, if you want to connect not as localhost, you can specify the binding address to connect to server. I.e:

client, _ := net.Dial("tcp", "192.168.1.31:1234")

Upvotes: 1

Related Questions