How to perform network port scanning and service discovery in Go?

To perform network port scanning and service discovery in Go, you can use the net package to create network connections and the context package for managing timeouts and cancelation. Here's an example code that demonstrates the process:

package main import ( "context" "fmt" "net" "sort" ) func scanPort(ctx context.Context, host string, port int) string { conn, err := net.Dial("tcp", fmt.Sprintf("%s:%d", host, port)) if err != nil { return "" } defer conn.Close() return fmt.Sprintf("%d open", port) } func portScanner(ctx context.Context, host string, ports []int) []string { results := make(chan string) for _, port := range ports { go func(port int) { result := scanPort(ctx, host, port) if result != "" { results <- result } }(port) } var openPorts []string for { select { case result := <-results: openPorts = append(openPorts, result) case <-ctx.Done(): return openPorts } } } func main() { host := "localhost" ports := []int{22, 80, 443, 8080} ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second) defer cancel() openPorts := portScanner(ctx, host, ports) sort.Strings(openPorts) for _, result := range openPorts { fmt.Println(result) } }

In this example, the scanPort function tries to establish a TCP connection with the specified host and port. If the connection is successful, it returns a string indicating that the port is open.

The portScanner function creates a separate goroutine for each port and concurrently performs the scanning using scanPort. The results are sent to a channel, and the main goroutine listens on this channel for results or the cancellation signal from the context timeout.

The main function sets a timeout of 3 seconds (context.WithTimeout) and specifies the host and ports to scan. It then calls portScanner and prints the sorted list of open ports.

Please note that network scanning without proper authorization may have legal implications, so make sure to only perform this on systems and networks you have permission to scan.