Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get IP and Port from net.Addr when it could be a net.UDPAddr or net.TCPAddr

Tags:

go

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

like image 581
Jamie H Avatar asked Dec 10 '22 06:12

Jamie H


1 Answers

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)
}
like image 194
Flimzy Avatar answered May 09 '23 00:05

Flimzy