douge3830 2019-05-28 06:27
浏览 1186
已采纳

Golang检查TCP端口打开

I need to check if remote address has specific TCP ports open or not. I have chosen to use golang for this purpose. Here is my attempt so far:

func raw_connect(host string, ports []string) {
  for _, port := range ports {
     timeout := time.Second
     conn, err := net.DialTimeout("tcp", host + ":" + port, timeout)
     if err != nil {
        _, err_msg := err.Error()[0], err.Error()[5:]
        fmt.Println(err_msg)
     } else {
        msg, _, err := bufio.NewReader(conn).ReadLine()
        if err != nil {
           if err == io.EOF {
              fmt.Print(host + " " + port + " - Open!
")
           }
        } else {
           fmt.Print(host + " " + port + " - " + string(msg))
        }
        conn.Close()
     }
   }
 }

This is working just fine for TCP port when application (such as SSH) returns first a string, I read it and print it with no time.

However, when the application above TCP is waiting for command from the client first (such as HTTP), there is a timeout (if err == io.EOF clause).

This timeout is quite long. I would need to know immediately if the port is open or not.

Is there a more suitable technique for this purpose ?

Many thanks!

  • 写回答

1条回答

  • duan19805 2019-05-28 07:11
    关注

    To check the port, you can check if the connection was successful. For example:

    func raw_connect(host string, ports []string) {
        for _, port := range ports {
            timeout := time.Second
            conn, err := net.DialTimeout("tcp", net.JoinHostPort(host, port), timeout)
            if err != nil {
                fmt.Println("Connecting error:", err)
            }
            if conn != nil {
                defer conn.Close()
                fmt.Println("Opened", net.JoinHostPort(host, port))
            }
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?