TCP Listen + auto port (0)

1,594 views
Skip to first unread message

Péter Szilágyi

unread,
Mar 24, 2013, 2:12:19 PM3/24/13
to golang-nuts
Hi,

  I was wondering about the ListenTCP method call with automatic port selection. If I set the port to 0, the OS will pick one at random, which we can query from the listener socket (i.e. sock.Addr.(*net.TCPAddr).Port).

  Wouldn't a nicer design be to update the argument passed to listen with the port number (it it's a pointer anyway)?

I.e. doing this internally inside the listen method:
sock, err := ListenTCP(addr)
addr.Port = sock.Addr.(*net.TCPAddr).Port 

  The benefit would be that wrapping the listen in a higher level protocol wouldn't require bubbling up the port number with a different mechanism. Am I missing a reason why the original address shouldn't change? The only point in keeping the original 0 is to have multiple listen calls with the same struct, but I'd say that's the exception and not the general rule.

So, what are your takes on this? :)

Cheers,
  Peter

Dave Cheney

unread,
Mar 24, 2013, 7:33:15 PM3/24/13
to Péter Szilágyi, golang-nuts
How would this function report its port number ?

l, _ := net.Listen("tcp", "127.0.0.1:0") // listen on localhost
port := l.Addr().(*net.TCPAddr).Port
> --
> You received this message because you are subscribed to the Google Groups
> "golang-nuts" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to golang-nuts...@googlegroups.com.
> For more options, visit https://groups.google.com/groups/opt_out.
>
>

Péter Szilágyi

unread,
Mar 24, 2013, 9:54:14 PM3/24/13
to Dave Cheney, golang-nuts
Hi,

  Well, you got me there :) I started using the net package only about a week ago and didn't consider the general Listen function. Although I could argue that going for the lowest common denominator may not always be the best practice (i.e. if Listen cannot support it, does it mean ListenTCP shouldn't either?), but I'm more than willing to accept a uniform standard library with a little pain here and there. All in all I still think this might be worth a round of consideration (supporting this feature only for those that can actually report it in the args), but if it's decided to remain as is, I'll be completely happy. My inquiry was about the reasoning behind the choice, and as such, I'm completely satisfied with your argument :)

Have a nice evening,
  Peter
Reply all
Reply to author
Forward
0 new messages