douzhi1813 2018-05-19 18:12
浏览 1026
已采纳

如何从net.Addr获取IP和端口(可能是net.UDPAddr或net.TCPAddr)

I'm running a hybrid server which listens on both TCP and UDP and need to get the local port, remote IP address and remote port. Currently the way I'm checking if the underlying type is net.UDPAddr or a net.TCPAddr is the following:

// BAD: but not sure a better way
switch reflect.TypeOf(remoteAddr).String() {
case "*net.UDPAddr":
    p.SrcIP = remoteAddr.(*net.UDPAddr).IP.String()
    p.SrcPort = uint(remoteAddr.(*net.UDPAddr).Port)
    p.DstPort = uint(localAddr.(*net.UDPAddr).Port)
case "*net.TCPAddr":
    p.SrcIP = remoteAddr.(*net.TCPAddr).IP.String()
    p.SrcPort = uint(remoteAddr.(*net.TCPAddr).Port)
    p.DstPort = uint(localAddr.(*net.TCPAddr).Port)
}

I'm not the greatest fan of this, if anyone has any cleaner looking solutions that would be greatly appreciated

  • 写回答

1条回答 默认 最新

  • dshtze500055 2018-05-19 18:15
    关注

    No need for reflection, just do a proper type assertion switch instead:

    switch addr := remoteAddr.(type) {
    case *net.UDPAddr:
        p.SrcIP = addr.IP.String()
        p.SrcPort = uint(addr.Port)
        p.DstPort = uint(localAddr.(*net.UDPAddr).Port)
    case *net.TCPAddr:
        p.SrcIP = addr.IP.String()
        p.SrcPort = uint(addr.Port)
        p.DstPort = uint(localAddr.(*net.TCPAddr).Port)
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 ssh登录页面的问题
  • ¥60 渗透一个指定银行app,拿到客户信息,需要什么级别
  • ¥50 关于在matlab上对曲柄摇杆机构上一点的运动学仿真
  • ¥15 jetson nano
  • ¥15 :app:debugCompileClasspath'.
  • ¥15 windows c++内嵌qt出现数据转换问题。
  • ¥20 公众号如何实现点击超链接后自动发送文字
  • ¥15 用php隐藏类名和增加类名
  • ¥15 算法设计与分析课程的提问
  • ¥15 用MATLAB汇总拟合图