Go Write a Simple TCP Scanner

2021年11月17日 50点热度 0人点赞 0条评论
内容目录

scanme.nmap.org is the domain or IP address to be scanned.

package main

import (
	"fmt"
	"net"
	"sort"
)

func main() {
	ports := make(chan int, 100)
	results := make(chan int)
	var openports []int
	// Start 100 worker threads
	for i := 0; i < cap(ports); i++ {
		go worker(ports, results)
	}
	// Write the ports to scan into the channel
	go func() {
		for i := 1; i <= 1024; i++ {
			ports <- i
		}
	}()
	// Receive ports from the channel
	// Worker threads must write to the results channel regardless of success or failure, or this will block
	for i := 1; i <= 1024; i++ {
		port := <-results
		if port != 0 {
			openports = append(openports, port)
		}
	}
	// Close all channels
	close(ports)
	close(results)

	// Sort the open ports
	sort.Ints(openports)
	for _, port := range openports {
		fmt.Printf("%d open \n", port)
	}
}

// Worker thread
func worker(ports, results chan int) {
	// Receive port value, if available then execute, if not then block
	for p := range ports {
		// Scan port
		// Each scan must write data to results, failure writes 0, success returns port value;
		address := fmt.Sprintf("scanme.nmap.org:%d", p)
		conn, err := net.Dial("tcp", address)
		if err != nil {
			results <- 0
			return
		}
		_ = conn.Close()
		results <- p
	}
}

痴者工良

高级程序员劝退师

文章评论