英文:
How to find the ports that is being used by a process in golang or in general?
问题
我的二进制文件接受一个端口参数,并启动一个HTTP服务器。如果将0传递给-port参数,它将找到一个空闲端口并在其上启动。
在此之后,如果我有命令对象和进程ID,我该如何找到使用的端口?我正在尝试使用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.
答案1
得分: 5
这是操作系统特定的,但在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
英文:
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论