GoNmap Scanner

Discover hosts on network + if selected ports are open

package main

import (
	"context"
	"fmt"
	"log"
	"time"

	"github.com/Ullaakut/nmap"
)

func main() {

	// ip range to scan
	tIP := "192.168.17.1/24"
	ctx, cancel := context.WithTimeout(context.Background(), 1*time.Minute)
	defer cancel()

	scanner, err := nmap.NewScanner(
		nmap.WithTargets(tIP),
		// ports to scan
		nmap.WithPorts("22", "80", "443"),
		nmap.WithContext(ctx),
	)

	if err != nil {
		log.Fatal("error : ", err)
	}

	results, warning, err := scanner.Run()

	if err != nil {
		log.Fatal("error : ", err)
	}

	if warning != nil {
		log.Fatal("error : ", warning)
	}

	for _, host := range results.Hosts {
		if len(host.Ports) == 0 || len(host.Addresses) == 0 {
			continue
		}

		fmt.Printf("IP: %q\n", host.Addresses[0])
		//if len(host.Addresses) > 1 {
		//	fmt.Printf("MAC: %v\n", host.Addresses[1])
		//}

		for _, port := range host.Ports {
			fmt.Printf("\tPort %d %s %s %s\n", port.ID, port.Protocol, port.State, port.Service.Name)

		}
	}

}

Last updated