Golang检查TCP端口打开

我需要检查远程地址是否打开了特定的TCP端口。

我已选择为此目的使用golang。
到目前为止,这是我的尝试:</ p>

  func raw_connect(host string,ports [] string){
表示_, port:=范围端口{
超时:= 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)
}其他{
msg,_,err:= bufio.NewReader(conn) .ReadLine()
if err!= nil {
if err == io.EOF {
fmt.Print(host +“” + port +“-Open!
”)
}
} else {
fmt.Print(host +“” +端口+“-” +字符串(msg))
}
conn.Close()
}
}
}
</ code> </ n> pre>

当应用程序(例如SSH)首先返回一个字符串时,这对于TCP端口来说就很好,我立即读取并打印了它。</ p>

但是,当TCP之上的应用程序首先等待来自客户端的命令(例如HTTP)时,会出现超时( if err == io.EOF </ code>子句)。</ p>

此超时时间很长。 我需要立即知道端口是否打开。</ p>

是否有更合适的技术用于此目的?</ p>

非常感谢! / p>
</ div>

展开原文

原文

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个回答



要检查端口,可以检查连接是否成功。 例如:</ p>

  func raw_connect(主机字符串,端口[]字符串){
表示_,端口:=范围端口{
超时:=时间。秒
conn,err:= net.DialTimeout(“ tcp”,net.JoinHostPort(主机,端口),超时)
如果err!= nil {
fmt.Println(“连接错误:”,err)
} \ n如果conn!= nil {
延迟conn.Close()
fmt.Println(“ Opened”,net.JoinHostPort(主机,端口))
}
}
}
</ code> < / pre>
</ div>

展开原文

原文

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

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问
相关内容推荐