package main
import (
"fmt"
"net"
"time"
)
func checkUDPPort(address string, timeout time.Duration) (bool, time.Duration) {
var conn net.Conn
var err error
start := time.Now()
conn, err = net.DialTimeout("udp", address, timeout)
if err != nil {
// fmt.Println("DialTimeout error:", err)
return false, time.Since(start)
}
defer conn.Close()
// Send a message to the server
_, err = conn.Write([]byte("Hello, World!"))
if err != nil {
// fmt.Println("Write error:", err)
return false, time.Since(start)
}
// Set a deadline for reading
conn.SetReadDeadline(time.Now().Add(timeout))
// Try to read from the server
buf := make([]byte, 1024)
_, err = conn.Read(buf)
if err != nil {
// fmt.Println("Read error:", err)
return false, time.Since(start)
}
return true, time.Since(start)
}
// checkPort 检测端口是否开放
func checkTCPPort(address string, timeout time.Duration) (bool, time.Duration) {
start := time.Now()
conn, err := net.DialTimeout("tcp", address, timeout)
if err != nil {
// fmt.Println(err)
return false, time.Since(start)
}
conn.Close()
return true, time.Since(start)
}
func main() {
ports := []int{22, 23, 53, 80, 443, 10080, 3306, 25}
addr := "192.168.140.3"
timeout := 1 * time.Second
for _, port := range ports {
address := fmt.Sprintf("%s:%d", addr, port)
// 检测TCP端口
isOpen, duration := checkTCPPort(address, timeout)
fmt.Printf("TCP %s open: %t (checked in %s)\n", address, isOpen, duration)
}
for _, port := range ports {
address := fmt.Sprintf("%s:%d", addr, port)
// 检测UDP端口
isOpen, duration := checkUDPPort(address, timeout)
fmt.Printf("UDP %s open: %t (checked in %s)\n", address, isOpen, duration)
}
}
注意:
由于UDP协议的无连接特性,单纯发送数据包并等待响应可能无法判断端口是否开放。
许多UDP服务不会响应任何的UDP数据包,而只有在收到特定格式的数据包后才会响应。
可以使用UDP探测工具,例如Nmap,这样的工具能够更好地检测UDP端口的状态。
标签:timeout,err,fmt,time,端口,start,测试,address,go From: https://www.cnblogs.com/guangdelw/p/18305754