Trying to determine what the connect error is and return value back to program.
d := net.Dialer{Timeout: 20*time.Second}
conn, errors := d.Dial("tcp", fmt.Sprintf("%v:%v", host, port))
if errors != nil {
if oerr, ok := errors.(*net.OpError); ok {
ErrorType := reflect.TypeOf(oerr.Err)
switch ErrorType.(type) {
case *os.SyscallError:
fmt.Println("connect: connection timed out to", host, "on port", port )
case *poll.TimeoutError:
fmt.Println("connect: connection refused to", host, "on port", port )
default:
panic("Unknown connection errot")
}
}
} else {
fmt.Println("connect: connection successful to", host, "on port", port )
}
if conn != nil {
conn.Close()
}
Get the follow error # command-line-arguments ./main.go:33:9: impossible type switch case: ErrorType (type reflect.Type) cannot have dynamic type *os.SyscallError (missing Align method) ./main.go:35:15: undefined: poll
You have no need to use reflect here. You need just type assertion language construction:
conn, errors := d.Dial("tcp", fmt.Sprintf("%v:%v", host, port))
if oerr, ok := errors.(*net.OpError); ok {
switch oerr.Err.(type) {
case os.SyscallError:
...
}
}
Keep in mind, you can't case the poll.TimeoutError because the poll package is internal and you can't import it. Regardless of all the above, if you want to check, if the error is related to timeout you should use Timeout method which is defined on the net.OpError
This code is not elegant but works now.
package main
import (
"flag"
"fmt"
"net"
"os"
"time"
)
// Run the port scanner
func main() {
var host, port string
flag.StringVar(&host, "H", "", "host to scan")
flag.StringVar(&port, "p", "", "port to scan")
flag.Parse()
if host == "" || port == "" {
fmt.Println("Usage: portscan -H <host> -p port")
os.Exit(1)
}
d := net.Dialer{Timeout: 20*time.Second}
conn, errors := d.Dial("tcp", fmt.Sprintf("%v:%v", host, port))
if errors != nil {
if oerr, ok := errors.(*net.OpError); ok {
switch oerr.Err.(type) {
case *os.SyscallError:
fmt.Println("connect: connection refused to", host, "on port", port )
default:
if oerr.Timeout() {
fmt.Println("connect: connection timed out to", host, "on port", port )
} else {
panic("Unknown connection error")
}
}
}
} else {
fmt.Println("connect: connection successful to", host, "on port", port )
}
if conn != nil {
conn.Close()
}
}