Best way to grep substring from a string before a character or string in golang

huangapple go评论88阅读模式
英文:

Best way to grep substring from a string before a character or string in golang

问题

我得到的net.Conn.RemoteAddr()是这样的:

192.168.16.96:64840

我只需要IP地址,不需要端口号

...
str := conn.RemoteAddr().String()
strSlice := strings.Split(str, ":")
ipAddress := strSlice[0]
...

有没有更简单的方法?

英文:

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?

答案1

得分: 11

你可以使用net.SplitHostPort函数,像这样:

ip, _, err := net.SplitHostPort(conn.RemoteAddr().String())
if err != nil {
    fmt.Println(err)
    return
}
fmt.Println(ip)

你可以在kbd上尝试一下。

回答上面评论中的问题,net.SplitHostPort函数已经处理了IPv6。给定字符串:

net.SplitHostPort("[2001:db8:85a3:0:0:8a2e:370]:7334")

会按预期工作。

英文:

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(&quot;[2001:db8:85a3:0:0:8a2e:370]:7334&quot;)

Will work as intended.

huangapple
  • 本文由 发表于 2016年3月16日 13:15:21
  • 转载请务必保留本文链接:https://go.coder-hub.com/36027315.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定