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

如何从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)
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?