Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

UDPConn.LocalAddr() returns a net.Addr that prints like a net.UDPAddr #53132

Closed
rcaputo opened this issue May 28, 2022 · 1 comment
Closed

UDPConn.LocalAddr() returns a net.Addr that prints like a net.UDPAddr #53132

rcaputo opened this issue May 28, 2022 · 1 comment

Comments

@rcaputo
Copy link

rcaputo commented May 28, 2022

The following sample program is currently also available at https://go.dev/play/p/KX6uPkxjFy_w

package main

import (
	"fmt"
	"net"
)

func main() {
	udpServerAddr, err := net.ResolveUDPAddr("udp", "127.0.0.1:0")
	if err != nil {
		panic(err)
	}
	udpServer, err := net.ListenUDP("udp", udpServerAddr)
	fmt.Printf("udpServer is a %T\n", udpServer)
	localAddr := udpServer.LocalAddr()
	fmt.Printf("localAddr is a %T, value %#v, string %s\n", localAddr, localAddr, localAddr)
	//fmt.Printf("localPort is %d\n", localAddr.Port)
}

fmt sees localAddr as a net.UDPAddr:

udpServer is a *net.UDPConn
localAddr is a *net.UDPAddr, value &net.UDPAddr{IP:net.IP{0x7f, 0x0, 0x0, 0x1}, Port:46866, Zone:""}, string 127.0.0.1:46866

Uncommenting line 19 breaks the program because localAddr is not what fmt says:

./prog.go:19:44: localAddr.Port undefined (type net.Addr has no field or method Port)
@seankhliao
Copy link
Member

net.Addr is an interface that could have many concrete implementations, including net.UDPAddr. There are no requirements on the String() formatting.
If you want the port, type assert it.

closing as not a bug.

For questions please refer to https://github.com/golang/go/wiki/Questions

@golang golang locked and limited conversation to collaborators May 28, 2023
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Projects
None yet
Development

No branches or pull requests

3 participants