golang简单判断22-65535端口开放情况

package main

import (
	"fmt"
	"net"
	"sync"
	"time"
)

func main() {
	server := "42.51.129.175"   // 要检查的服务器地址
	ports := make([]int, 65535) // 要检查的端口范围,从22到65535
	for i := 22; i <= 65535; i++ {
		ports[i-22] = i
	}

	var wg sync.WaitGroup
	wg.Add(len(ports))

	for _, port := range ports {
		go func(port int) {
			address := fmt.Sprintf("%s:%d", server, port)
			conn, err := net.DialTimeout("tcp", address, time.Second*2)
			//if err != nil {
			//	fmt.Printf("端口 %d 关闭\n", port)
			//} else {
			//	defer conn.Close()
			//	fmt.Printf("端口 %d 开放\n", port)
			//}
			if err == nil {
				defer conn.Close()
				fmt.Printf("端口 %d 开放\n", port)
			}
			wg.Done()
		}(port)
	}
	wg.Wait()
}

posted @ 2023-12-21 15:51  朝阳1  阅读(17)  评论(0编辑  收藏  举报