持续检查TCP端口是否正在使用。

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

Continuously check if tcp port is in use

问题

我正在运行一个bash命令来在后台启动一个服务器:"./starServer &"。然而,我的服务器需要几秒钟的时间来启动。我想知道在实际继续执行其他操作之前,我可以做些什么来持续检查它所运行的端口,以确保它已经启动。我在golang API中找不到任何有用的内容。感谢任何帮助!

c := exec.Command("/bin/sh", "-c", command)
err := c.Start()
if err != nil {
log.Fatalf("error: %v", err)
}
l, err1 := net.Listen("tcp", ":"+port)

英文:

I'm running a bash command to start up a server in the background : "./starServer &" However, my server takes a few seconds to start up. I'm wondering what I can do to continuously check the port that it's running on to ensure it's up before I actually move on and do other things. I couldn't find anything in the golang api that helped with this. Any help is appreciated!

c := exec.Command("/bin/sh", "-c", command)
err := c.Start()
if err != nil {
	log.Fatalf("error: %v", err)
}
l, err1 := net.Listen("tcp", ":" + port)

答案1

得分: 18

你可以使用net.DialTimeoutnet.Dial连接到端口,如果成功,立即关闭连接。你可以在一个循环中执行这个操作,直到成功。

for {
    conn, err := net.DialTimeout("tcp", net.JoinHostPort("", port), timeout)
    if conn != nil {
        conn.Close()
        break
    }
}

我写了一个类似目的的简单小型库,也许你会感兴趣:portping

英文:

You could connect to the port using net.DialTimeout or net.Dial, and if successful, immediately close it. You can do this in a loop until successful.

for {
	conn, err := net.DialTimeout("tcp", net.JoinHostPort("", port), timeout)
	if conn != nil {
		conn.Close()
        break
	}
}

A simple tiny library (I wrote) for a similar purpose might also be of interest: portping.

huangapple
  • 本文由 发表于 2016年10月28日 09:13:02
  • 转载请务必保留本文链接:https://go.coder-hub.com/40296483.html
匿名

发表评论

匿名网友

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

确定