Aila
Aila

Reputation: 329

How to find the ports that is being used by a process in golang or in general?

My binary takes a port parameter and starts a http server. If pass a 0 to the -port, it will find a free port and start on it.

After this, how do I find which port is this if I have the command object with me and can get the process id? I am trying to write my application in golang. I am also curious how this is done in general.

Upvotes: 3

Views: 4448

Answers (1)

David Budworth
David Budworth

Reputation: 11626

It's OS specific, but on linux you can do

netstat -npl

that will list which programs are listening on which ports

If you just want to print it out from your app, you can use the alternative form of starting the http server by creating your own tcp listener and then call http.Serve

example:

package main

import (
    "fmt"
    "net"
    "net/http"
    "os"
)

func main() {
    lsnr, err := net.Listen("tcp", ":0")
    if err != nil {
        fmt.Println("Error listening:", err)
        os.Exit(1)
    }
    fmt.Println("Listening on:", lsnr.Addr())
    err = http.Serve(lsnr, nil)
    fmt.Println("Server exited with:", err)
    os.Exit(1)
}

outputs:

Listening on: [::]:53939

Upvotes: 5

Related Questions