Skip to content

Instantly share code, notes, and snippets.

@songtianyi
Last active July 3, 2020 10:52
Show Gist options
  • Save songtianyi/e5953610eab629b3444463f26635b9e5 to your computer and use it in GitHub Desktop.
Save songtianyi/e5953610eab629b3444463f26635b9e5 to your computer and use it in GitHub Desktop.
udp/tcp port open check
package main
import (
"fmt"
"net"
"strings"
"time"
"github.com/ziutek/telnet"
)
func check_udp(ip1, ip2, ip3, ip4 byte, port int) bool {
conn, err := net.DialUDP("udp", nil, &net.UDPAddr{net.IPv4(ip1, ip2, ip3, ip4), port, ""})
if err != nil {
fmt.Println(err)
return false
}
defer conn.Close()
conn.Write([]byte(""))
buffer := make([]byte, 1024)
conn.SetReadDeadline(time.Now().Add(3 * time.Second))
_, _, err = conn.ReadFrom(buffer)
if err != nil {
fmt.Println("readfrom", err)
return !strings.Contains(err.Error(), "recvfrom: connection refused")
}
return true
}
func check_tcp(addr string) bool {
_, err := telnet.DialTimeout("tcp", addr, 5*time.Second)
if err != nil {
fmt.Println(err)
return false
}
return true
}
func main() {
fmt.Println(check_udp(192, 168, 1, 99, 123)) // true
fmt.Println(check_udp(192, 168, 1, 99, 234)) // false
fmt.Println(check_tcp("192.168.1.99:1234")) // false
fmt.Println(check_tcp("192.168.1.99:8081")) // true
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment