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

huangapple go评论88阅读模式
英文:

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

huangapple
  • 本文由 发表于 2015年4月29日 08:29:16
  • 转载请务必保留本文链接:https://go.coder-hub.com/29932291.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定