golang scan tcp ports
golang scan tcp ports
func TCPPortScan(ip string) (out string) {
portIgnore := []int{22, 3389, 10050, 19100}
cd := time.Second * 3
goLimit := make(chan struct{}, 1000)
var syncMap sync.Map
var wg sync.WaitGroup
wg.Add(65535)
for port := 1; port <= 65535; port++ {
if inIntSlice(portIgnore, port) {
//白名单不测 计数器 -1
wg.Done()
continue
}
go func() {
goLimit <- struct{}{}
//200ms认为超时
if portDialRaw(ip, strconv.Itoa(port), "tcp", cd) {
syncMap.Store(port, port)
}
// 计数器 -1
wg.Done()
<-goLimit
}()
}
//等待所有端口扫描完成 阻塞。计数器为 0 的时候,Wait 返回
wg.Wait()
close(goLimit)
return syncMapSort(&syncMap)
}
func syncMapSort(syncMap *sync.Map) string {
var intList []int
// Range遍历所有sync.Map中的键值对
syncMap.Range(func(k, v any) bool {
if intValue, ok := k.(int); ok {
intList = append(intList, intValue)
}
return true
})
sort.Ints(intList)
var out string
for _, value := range intList {
out = out + " " + strconv.Itoa(value)
}
return strings.TrimLeft(out, " ")
}