试图确定什么是连接错误,然后将值返回给程序。
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()
}
获取关注错误 #个命令行参数 ./main.go:33:9:类型切换不可能的情况:ErrorType(类型reflect.Type)不能具有动态类型* os.SyscallError(缺少Align方法) ./main.go:35:15:未定义:民意调查
答案 0 :(得分:0)
您无需在此处使用反射。您只需要输入类型声明语言即可:
annoucementString
请记住,您不能使用poll.TimeoutError的情况,因为poll包是内部的,您不能导入它。 不管上述情况如何,如果要检查错误是否与超时有关,则应使用在net.OpError
上定义的Timeout方法。答案 1 :(得分:0)
此代码并不美观,但现在可以使用。
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()
}
}