How to Implement a Port Scanner in Go

Web
Implement a Go port scanner by using net.DialTimeout to check if a specific TCP port on a target host accepts connections.

Use the net package to dial a TCP connection to a target IP and port, then report success or failure based on the error.

package main

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

func scanPort(host string, port int) bool {
	addr := fmt.Sprintf("%s:%d", host, port)
	conn, err := net.DialTimeout("tcp", addr, 2*time.Second)
	if err != nil {
		return false
	}
	conn.Close()
	return true
}

func main() {
	if scanPort("127.0.0.1", 80) {
		fmt.Println("Port 80 is open")
	}
}