Get the port of a running http server?

4,647 views
Skip to first unread message

Lucas

unread,
Jul 7, 2011, 5:46:55 PM7/7/11
to golang-nuts
Hi,

I'm writing an HTTP based service using the 'http' package. For unit/
system testing I figured I would start the service with the address
set to "localhost:0", assuming that using port zero would give me an
OS assigned free port (avoiding making assumptions about what's
currently running on the system and what ports are free). This works,
the server starts, and you can see it's been bound to a random port
using the OS's tools, but how do I programmatically ask the http
package server what port its bound to?

Am I taking the wrong approach to this? Does Go solve this problem
some other way?

Thanks,
-Lucas

Kyle Lemons

unread,
Jul 7, 2011, 6:23:52 PM7/7/11
to Lucas, golang-nuts
Have a look at net.Conn.Addr().(TCPAddr).Port

~K

Kyle Lemons

unread,
Jul 7, 2011, 6:24:53 PM7/7/11
to Lucas, golang-nuts
I meant LocalAddr(), sorry about that.

Lucas

unread,
Jul 7, 2011, 7:01:07 PM7/7/11
to golang-nuts
Thanks for the response. I'm fairly new to Go, so just to confirm my
conclusion:

If you started the http server using "http.ListenAndServe()" function,
it's not possible to programatically get at the internal connection/
socket stuff (I can't seem to find any accessors functions for the
internals).

So instead you have to create the listener yourself and bind/serve it
by hand, and then give it to the http.Serve function

listner, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
log.Fatal("Listen:", err)
}

err2 := http.Serve(listner, nil)
if err2 != nil {
log.Fatal("http.Serve:", err2)
}

At this point the socket has been bound, and you can get it's new
port:

fmt.Printf("%s", listner.Addr().String());


Or is there an easier way that I'm just not seeing?

Thanks,
-Lucas

On Jul 7, 3:24 pm, Kyle Lemons <kev...@google.com> wrote:
> I meant LocalAddr() <http://golang.org/pkg/net/#Conn>, sorry about that.
>
>
>
>
>
>
>
> On Thu, Jul 7, 2011 at 3:23 PM, Kyle Lemons <kev...@google.com> wrote:
> > Have a look at net.Conn.Addr().(TCPAddr).Port<http://golang.org/pkg/net/#TCPAddr>
>
> > ~K

Kyle Lemons

unread,
Jul 7, 2011, 7:06:42 PM7/7/11
to Lucas, golang-nuts
    listner, err := net.Listen("tcp", "127.0.0.1:0")
    if err != nil {
        log.Fatal("Listen:", err)
    }

Your listener will be bound here, so you can print out the address 
 
    err2 := http.Serve(listner, nil)
    if err2 != nil {
        log.Fatal("http.Serve:", err2)
    }

This goes into an infinite loop, so until it fails, your code won't continue past this Serve().

~K 
Reply all
Reply to author
Forward
0 new messages