drqyxkzbs21968684 2016-03-16 05:15
浏览 295
已采纳

从golang中的字符或字符串之前的字符串grep子字符串的最佳方法

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条回答 默认 最新

  • dongtan8532 2016-03-16 06:04
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?