masscan

package module
v1.0.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Feb 28, 2026 License: MIT Imports: 12 Imported by: 0

README

masscan

MIT license PkgGoDev github.com/Ullaakut/masscan Go Report Card

This library provides idiomatic masscan bindings for Go developers. It shells out to the masscan binary and parses scan output into Go structs.

What is masscan

Masscan is a high-speed TCP port scanner focused on quickly identifying open ports across large target ranges. Compared to nmap, masscan prioritizes speed and broad coverage over deep service fingerprinting.

How it works

  • The package executes masscan via os/exec.
  • masscan must be installed and available in your PATH (or configured with WithBinaryPath).
  • The scanner runs synchronously with Run(ctx).
  • Output is parsed into Run, Host, and Port structs.

Supported output formats

The parser supports these formats:

  • JSON (-oJ) — recommended default
  • XML (-oX)
  • List (-oL)
  • Grepable (-oG)
  • Plain discovered lines from stdout (fallback parsing)

Binary output (-oB) is not parsed directly and returns ErrUnsupportedOutputFormat.

Privileges

Masscan usually requires raw socket privileges. If you see ErrRequiresRoot, run with elevated privileges (for example, via sudo) or configure capabilities for your environment.

Installation

go get github.com/Ullaakut/masscan

Quick start

package main

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

	"github.com/Ullaakut/masscan"
)

func main() {
	ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
	defer cancel()

	scanner, err := masscan.NewScanner(
		masscan.WithTargets("scanme.nmap.org"),
		masscan.WithPorts("80", "443"),
		masscan.WithRate(1000),
		masscan.WithWait(3),
		masscan.WithOutputFormat(masscan.OutputFormatJSON),
	)
	if err != nil {
		log.Fatalf("unable to create scanner: %v", err)
	}

	result, err := scanner.Run(ctx)
	if err != nil {
		log.Fatalf("scan failed: %v", err)
	}

	for _, warning := range result.Warnings() {
		log.Printf("warning: %s", warning)
	}

	for _, host := range result.Hosts {
		for _, port := range host.Ports {
			fmt.Printf("%s %d/%s %s\n", host.Address, port.Number, port.Protocol, port.Status)
		}
	}
}

Options API

The package provides typed options for common masscan flags, including:

  • WithTargets, WithPorts, WithTopPorts
  • WithExclude, WithExcludeFile
  • WithRate, WithWait, WithOpenOnly
  • WithInterface, WithSourceIP, WithSourcePort
  • WithAdapterIP, WithAdapterPort, WithAdapterMAC, WithRouterMAC
  • WithShard, WithSeed, WithResumeIndex, WithResumeCount
  • WithBanners, WithPing, WithDebug
  • WithOutputFormat

If a masscan flag is not covered yet, use:

  • WithRawFlag("--some-flag")
  • WithRawOption("--some-option", "value")

Examples

Run an example:

go run ./examples/basic_scan/main.go

For privileged scans:

sudo env "PATH=$PATH" go run ./examples/basic_scan/main.go

Error handling

Common sentinel errors include:

  • ErrMasscanNotInstalled
  • ErrScanTimeout
  • ErrScanInterrupt
  • ErrParseOutput
  • ErrInvalidOutput
  • ErrUnsupportedOutputFormat
  • ErrRequiresRoot
  • ErrResolveName
  • ErrMallocFailed

External resources

Documentation

Overview

Package masscan provides idiomatic `masscan` bindings for go developers.

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrMasscanNotInstalled means that upon trying to manually locate masscan in the user's path,
	// it was not found. Either use the WithBinaryPath method to set it manually, or make sure that
	// the masscan binary is present in the user's $PATH.
	ErrMasscanNotInstalled = errors.New("masscan binary was not found")

	// ErrScanTimeout means that the provided context timeout triggered done before the scanner finished its scan.
	// This error is *not* returned if a scan timeout was configured using Masscan arguments, since Masscan would
	// gracefully shut down it's scanning and return some results in that case.
	ErrScanTimeout = errors.New("masscan scan timed out")

	// ErrScanInterrupt means that the scan was interrupted before the scanner finished its scan.
	// Reasons for this error might be sigint or a cancelled context.
	ErrScanInterrupt = errors.New("masscan scan interrupted")

	// ErrParseOutput means that masscan's output was not parsed successfully.
	ErrParseOutput = errors.New("masscan output parsing failure, see warnings for details")

	// ErrUnsupportedOutputFormat means that the requested masscan output format
	// cannot be parsed by this package.
	ErrUnsupportedOutputFormat = errors.New("unsupported masscan output format")

	// ErrInvalidOutput means that masscan returned output that could not be decoded.
	ErrInvalidOutput = errors.New("invalid masscan output")

	// ErrMallocFailed means that masscan failed because it could not allocate memory.
	ErrMallocFailed = errors.New("masscan malloc failed")

	// ErrRequiresRoot means that a feature (e.g. OS detection) requires root privileges.
	ErrRequiresRoot = errors.New("this feature requires root privileges")

	// ErrResolveName means that masscan could not resolve a name.
	ErrResolveName = errors.New("masscan could not resolve a name")
)

Functions

This section is empty.

Types

type Host

type Host struct {
	Address   string
	Timestamp string
	Ports     []Port
}

Host represents a discovered host.

type Option

type Option func(*Scanner) error

Option configures a Scanner by adding or changing masscan arguments.

func WithAdapterIP

func WithAdapterIP(adapterIP string) Option

WithAdapterIP sets adapter IP address (--adapter-ip).

func WithAdapterMAC

func WithAdapterMAC(mac string) Option

WithAdapterMAC sets adapter MAC address (--adapter-mac).

func WithAdapterPort

func WithAdapterPort(port int) Option

WithAdapterPort sets adapter/source port (--adapter-port).

func WithBanners

func WithBanners() Option

WithBanners enables banner grabbing (--banners).

func WithBinaryPath

func WithBinaryPath(binaryPath string) Option

WithBinaryPath sets the masscan binary path for a scanner.

func WithConfigPath

func WithConfigPath(config string) Option

WithConfigPath sets the configuration file path (--conf).

func WithDebug

func WithDebug() Option

WithDebug enables masscan debug mode (--debug).

func WithExclude

func WithExclude(excludes ...string) Option

WithExclude excludes targets from scan (--exclude).

func WithExcludeFile

func WithExcludeFile(path string) Option

WithExcludeFile excludes targets from a file (--excludefile).

func WithFilterHost

func WithFilterHost(hostFilter func(Host) bool) Option

WithFilterHost allows to set a custom function to filter out hosts that don't fulfill a given condition. When the given function returns true, the host is kept, otherwise it is removed from the result. Can be used along with WithFilterPort.

func WithFilterPort

func WithFilterPort(portFilter func(Port) bool) Option

WithFilterPort allows to set a custom function to filter out ports that don't fulfill a given condition. When the given function returns true, the port is kept, otherwise it is removed from the result. Can be used along with WithFilterHost.

func WithInterface

func WithInterface(iface string) Option

WithInterface sets outgoing interface (--interface).

func WithOpenOnly

func WithOpenOnly() Option

WithOpenOnly limits output to open ports only (--open-only).

func WithOutputFormat

func WithOutputFormat(format OutputFormat) Option

WithOutputFormat sets output format for parsing. If explicit -o* args are passed, masscan will use them instead.

func WithPing

func WithPing() Option

WithPing scans in ping mode only (--ping).

func WithPorts

func WithPorts(ports ...string) Option

WithPorts sets ports to scan (-p).

func WithRate

func WithRate(maxRate int) Option

WithRate sets packet sending rate (--rate).

func WithRawFlag

func WithRawFlag(flag string) Option

WithRawFlag appends a raw masscan flag with no value.

func WithRawOption

func WithRawOption(flag, value string) Option

WithRawOption appends a raw masscan option and value pair.

func WithResumeCount

func WithResumeCount(count int) Option

WithResumeCount scans count from resumed point (--resume-count).

func WithResumeIndex

func WithResumeIndex(index int) Option

WithResumeIndex resumes from paused index (--resume-index).

func WithRouterMAC

func WithRouterMAC(mac string) Option

WithRouterMAC sets router MAC (--router-mac).

func WithSeed

func WithSeed(seed int) Option

WithSeed sets randomization seed (--seed).

func WithShard

func WithShard(x, y int) Option

WithShard enables distributed scanning (--shard).

func WithSourceIP

func WithSourceIP(sourceIP string) Option

WithSourceIP sets source IP address (--source-ip).

func WithSourcePort

func WithSourcePort(sourcePort int) Option

WithSourcePort sets source port (--source-port).

func WithTargets

func WithTargets(targets ...string) Option

WithTargets sets targets to scan (CIDR/range/single address/hostname).

func WithTopPorts

func WithTopPorts(count int) Option

WithTopPorts sets top port count (--top-ports).

func WithWait

func WithWait(delay int) Option

WithWait sets waiting time in seconds (--wait).

type OutputFormat

type OutputFormat string

OutputFormat is the output format produced by masscan.

const (
	OutputFormatJSON     OutputFormat = "json"
	OutputFormatXML      OutputFormat = "xml"
	OutputFormatList     OutputFormat = "list"
	OutputFormatGrepable OutputFormat = "grepable"
	OutputFormatBinary   OutputFormat = "binary"
	OutputFormatUnknown  OutputFormat = "unknown"
)

OutputFormat values supported by this package.

type Port

type Port struct {
	Number    int
	Protocol  string
	Status    string
	Reason    string
	ReasonTTL int
}

Port represents a discovered port.

type Run

type Run struct {
	Hosts []Host
	// contains filtered or unexported fields
}

Run represents the parsed output of a masscan execution.

func (*Run) Warnings

func (r *Run) Warnings() []string

Warnings returns parsing or runtime warnings emitted by masscan.

type ScanRunner

type ScanRunner interface {
	Run(ctx context.Context) (*Run, error)
}

ScanRunner represents something that can run a scan.

type Scanner

type Scanner struct {
	// contains filtered or unexported fields
}

Scanner represents a Masscan scanner.

func NewScanner

func NewScanner(options ...Option) (*Scanner, error)

NewScanner creates a new Scanner, and can take options to apply to the scanner.

func (*Scanner) AddOptions

func (s *Scanner) AddOptions(options ...Option) (*Scanner, error)

AddOptions sets more scan options after the scan is created.

func (*Scanner) Args

func (s *Scanner) Args() []string

Args return the list of masscan args.

func (*Scanner) Run

func (s *Scanner) Run(ctx context.Context) (*Run, error)

Run executes masscan with the enabled options and parses the resulting output.

func (*Scanner) ToFile

func (s *Scanner) ToFile(file string) (*Scanner, error)

ToFile enables the Scanner to write the masscan XML output to a given path. Masscan writes the normal CLI output to stdout. The XML is parsed from file after the scan is finished.

func (*Scanner) WithOutputFormat

func (s *Scanner) WithOutputFormat(format OutputFormat) (*Scanner, error)

WithOutputFormat sets the parser output preference when an explicit output flag is not already set.

Directories

Path Synopsis
examples
banner_scan command
basic_scan command
interface_scan command
internal

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL