1

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?

5
  • Simpler than 3 line? Commented Mar 16, 2016 at 5:16
  • 2
    ipAddress := strings.Split(conn.Remoteddr().String(), ":")[0] Commented Mar 16, 2016 at 5:17
  • @GarMan It still looks ugly.... :( Do I have to wrap these things by my self? Commented Mar 16, 2016 at 5:55
  • 1
    on a side note: OPs and GarMans code wouldn't work with IPv6 Commented Mar 16, 2016 at 8:36
  • @DanieleD So, if we get IPv6, how to solve the problem? Commented Mar 16, 2016 at 23:15

1 Answer 1

11

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 Playground

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.