I got net.Conn.RemoteAddr() as this:
192.168.16.96:64840
I only need IP address without port number
...
str := conn.RemoteAddr().String()
strSlice := strings.Split(str, ":")
ipAddress := strSlice[0]
...
Is there any simple way?
I got net.Conn.RemoteAddr() as this:
192.168.16.96:64840
I only need IP address without port number
...
str := conn.RemoteAddr().String()
strSlice := strings.Split(str, ":")
ipAddress := strSlice[0]
...
Is there any simple way?
You can use net.SplitHostPort
, like so
ip, _, err := net.SplitHostPort(conn.RemoteAddr().String())
if err != nil {
fmt.Println(err)
return
}
fmt.Println(ip)
Try it on the <kbd>Playground</kbd>
To answer OP's question in the comments above, net.SplitHostPort
already deals with IPv6. Given the string
net.SplitHostPort("[2001:db8:85a3:0:0:8a2e:370]:7334")
Will work as intended.