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.

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

报告相同问题?

悬赏问题

  • ¥15 宇视监控服务器无法登录
  • ¥15 PADS Logic 原理图
  • ¥15 PADS Logic 图标
  • ¥15 电脑和power bi环境都是英文如何将日期层次结构转换成英文
  • ¥15 DruidDataSource一直closing
  • ¥20 气象站点数据求取中~
  • ¥15 如何获取APP内弹出的网址链接
  • ¥15 wifi 图标不见了 不知道怎么办 上不了网 变成小地球了
  • ¥50 STM32单片机传感器读取错误
  • ¥50 power BI 从Mysql服务器导入数据,但连接进去后显示表无数据