title: golang check tcp port open
body: <p>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:</p>
  
  <pre><code>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!\n")
             }
          } else {
             fmt.Print(host + " " + port + " - " + string(msg))
          }
          conn.Close()
       }
     }
   }
  </code></pre>
  
  <p>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.</p>
  
  <p>However, when the application above TCP is waiting for command from the client first (such as HTTP), there is a timeout (<code>if err == io.EOF</code> clause).</p>
  
  <p>This timeout is quite long. I would need to know immediately if the port is open or not.</p>
  
  <p>Is there a more suitable technique for this purpose ?</p>
  
  <p>Many thanks!</p>