如何在golang或一般情况下找到进程正在使用的端口?

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.

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