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

时间:2015-04-29 00:29:16

标签: shell go port pid

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.

1 个答案:

答案 0 :(得分:3)

这是特定于操作系统的,但在linux上你可以做到

netstat -npl

将列出哪些程序正在侦听哪些端口

如果您只想从应用程序中打印出来,可以使用另一种形式启动http服务器,方法是创建自己的tcp侦听器,然后调用http.Serve

示例:

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)
}

输出:

Listening on: [::]:53939