Courses3 levels
Level 1 · Foundations11 courses
Level 2 · Core5 courses
Level 3 · Advanced5 courses
Labs8 topics
Library Practice exams AI Range Pricing Start free

Lesson 08 · 45 minutes

Write a port scanner and test it against a listener

After this lesson you can
  • Scan a range of ports with a pool of workers and a context
  • Refuse every host that is not your own machine
  • Test the scanner against a listener that the test opens itself
Lab files of this lesson (33)

The lab folder as it stands after this lesson. Unzip it in ~/krlab.

More

The zip holds every file that the course has printed up to here. To start this lesson with the files of the earlier lessons only, take the zip of the lesson before. Type the code yourself first: you learn more.

Scenario

The first question in a review of a machine is: what is listening? Every open port is a door, and a forgotten door is a risk. Your lead wants a tool that answers it in seconds, that you can copy to a host as one file, and that has tests. In this lesson you write the engine of that tool, the package scan, and test it. Lesson 9 turns it into the command portcheck.

Only check systems that you own or have written permission to test. A scan of another system can be against the law and can set off alarms. Everything in this lesson stays on 127.0.0.1, your own machine. The package also enforces the rule: Local says whether a host is this machine, and the command of lesson 9 refuses any other host.

Recall

Lesson 7 found a bug that a table test had missed. How did it find it?

A fuzz test stated a rule (the number printed back gives the same text) and the fuzzer tried thousands of inputs until one broke it: a text such as "01" that is not plain digits.

Why does a worker pool close its job channel, and who should close it?

Closing the channel tells the workers that no more jobs come, so their range loops end. The sender closes it, once. A sender must never send on a closed channel.

The idea

A TCP port is open if a connection to it succeeds. The scanner connects and closes at once. It sends nothing. A pool of workers (lesson 6) dials the ports, and each dial has its own timeout from a context (lesson 5). A feeder sends the port numbers, and a closer shuts the result channel when every worker has finished, so the loop that collects the results ends.

How Scan finds the open ports
ScanFeederWorkersPortstart the feeder, the workers and the closerone port number at a timedial with a timeoutconnected means open, refused means closedeach open port, which Scan sortsScanFeederWorkersPort12345
  1. Scan → Feeder: start the feeder, the workers and the closer
  2. Feeder → Workers: one port number at a time
  3. Workers → Port: dial with a timeout
  4. Port → Workers: connected means open, refused means closed
  5. Workers → Scan: each open port, which Scan sorts

Worked example

1. Make the module

mkdir -p ~/krlab/go/portcheck/scan
cd ~/krlab/go/portcheck
go mod init krlab/portcheck

go mod init writes this go.mod. The lab zip holds it with go 1.22, so that it builds on every Go from 1.22:

go.mod

module krlab/portcheck

go 1.22

2. Write the scanner package

Write scan/scan.go. Scan starts workers goroutines that read port numbers from one channel. A feeder sends the numbers, and stops if the context ends. A closer shuts the result channel when the workers are done. Each dial has its own timeout context. Scan returns the open ports in order, and the error of the context, which is nil when the scan ran to the end. Local says whether a host is this machine: lesson 9 uses it to refuse other hosts. These names are new:

NameJob
net.DialerOpens connections.
DialContextOpens one connection, and stops when its context ends.
net.JoinHostPortJoins a host and a port into one address. It adds the brackets of an IPv6 address.
netip.ParseAddrReads an IP address. A name such as localhost gives an error.
addr.IsLoopback()True for an address of this machine: 127.0.0.1 and the other 127.x.x.x addresses, and ::1.
for range workersRepeats a block workers times (Go 1.22).

portcheck/scan/scan.go

package scan

import (
	"context"
	"net"
	"net/netip"
	"sort"
	"strconv"
	"sync"
	"time"
)

// Local reports whether host is this machine: "localhost" or a loopback address.
func Local(host string) bool {
	if host == "localhost" {
		return true
	}
	addr, err := netip.ParseAddr(host)
	return err == nil && addr.IsLoopback()
}

func Scan(ctx context.Context, host string, lo, hi, workers int, timeout time.Duration) ([]int, error) {
	ports := make(chan int)
	found := make(chan int)

	var wg sync.WaitGroup
	for range workers {
		wg.Add(1)
		go func() {
			defer wg.Done()
			var d net.Dialer
			for p := range ports {
				dctx, cancel := context.WithTimeout(ctx, timeout)
				conn, err := d.DialContext(dctx, "tcp", net.JoinHostPort(host, strconv.Itoa(p)))
				cancel()
				if err == nil {
					conn.Close()
					found <- p
				}
			}
		}()
	}
	go func() {
		defer close(ports)
		for p := lo; p <= hi; p++ {
			select {
			case ports <- p:
			case <-ctx.Done():
				return
			}
		}
	}()
	go func() {
		wg.Wait()
		close(found)
	}()

	var open []int
	for p := range found {
		open = append(open, p)
	}
	sort.Ints(open)
	return open, ctx.Err()
}

3. Test it against a local listener

Write scan/scan_test.go. The test opens a listener on port 0, so the system picks a free port. A listener that is opened and closed at once gives a port that is closed. TestLocal checks the rule of Local. These names are new:

NameJob
net.ListenOpens a listening port.
t.Helper()Makes a failure point at the caller.
t.Cleanup(f)Runs f when the test ends.
l.Addr().(*net.TCPAddr)A type assertion. l.Addr() has a general type. The assertion says "this is really a TCP address", so .Port works.
slices.EqualTells whether two slices hold the same values in the same order.

portcheck/scan/scan_test.go

package scan

import (
	"context"
	"net"
	"slices"
	"testing"
	"time"
)

func listen(t *testing.T, keep bool) int {
	t.Helper()
	l, err := net.Listen("tcp", "127.0.0.1:0")
	if err != nil {
		t.Fatal(err)
	}
	if keep {
		t.Cleanup(func() { l.Close() })
	} else {
		l.Close()
	}
	return l.Addr().(*net.TCPAddr).Port
}

func TestLocal(t *testing.T) {
	for host, want := range map[string]bool{
		"127.0.0.1": true, "::1": true, "localhost": true,
		"192.168.1.5": false, "example.test": false, "": false,
	} {
		if got := Local(host); got != want {
			t.Errorf("Local(%q) = %v, want %v", host, got, want)
		}
	}
}

func TestScan(t *testing.T) {
	open := listen(t, true)
	closed := listen(t, false)
	tests := []struct {
		name   string
		lo, hi int
		want   []int
	}{
		{"open port", open, open, []int{open}},
		{"closed port", closed, closed, nil},
		{"window around an open port", open - 3, open + 3, []int{open}},
	}
	for _, tc := range tests {
		t.Run(tc.name, func(t *testing.T) {
			got, err := Scan(context.Background(), "127.0.0.1", tc.lo, tc.hi, 4, time.Second)
			if err != nil {
				t.Fatal(err)
			}
			if !slices.Equal(got, tc.want) {
				t.Errorf("got %v, want %v", got, tc.want)
			}
		})
	}
}

-v prints each test and each case as it runs, and its result. The listing below keeps only the result lines. ./scan is the folder of the package.

go vet ./... && go test -race -v ./scan
--- PASS: TestLocal (0.00s)
--- PASS: TestScan (0.00s)
    --- PASS: TestScan/open_port (0.00s)
    --- PASS: TestScan/closed_port (0.00s)
    --- PASS: TestScan/window_around_an_open_port (0.00s)
PASS
ok  	krlab/portcheck/scan	1.027s

These tests do not cover a silent host, which needs a network that drops packets. Not tested here.

Your turn

Test two behaviours that the lesson did not test. Do not change scan.go. Add the tests to scan/scan_test.go, and run them with go test -race -v -count=1 -run 'Cancelled|Edges' ./scan (-run takes a pattern and runs the tests whose names match).

  1. TestScanCancelled. Open a listener that stays open. ctx, cancel := context.WithCancel(context.Background()) gives a context that ends when you call cancel(), as WithTimeout does at its deadline. Call cancel() before you call Scan on a window of seven ports around the listener. Check that the error matches context.Canceled (use errors.Is) and that no port is found. Print the error text and the number of ports with t.Logf, which shows only with -v.
  2. TestLocalEdges. For each of these hosts, print what Local says with t.Logf: 127.0.0.2, 0.0.0.0, ::ffff:127.0.0.1, [::1] and LOCALHOST. This test checks nothing. It shows where the rule draws its line.

Check yourself

Why does `Scan` use a worker pool and not one goroutine for each port?

A full range would open 65,535 connections at once. The system limits open files, and a flood gives false "closed" results. The pool keeps at most workers connections open.

Why does the test use port 0 and not a fixed port?

A fixed port may be in use on another machine, or by another test at the same time. Port 0 lets the system choose a free one, and the test reads the number from the listener.

`Local("LOCALHOST")` is false. Is that a fault?

It errs on the safe side: a host that the rule does not know is refused, and the user can give the exact name. A rule that decides what a tool may touch should refuse when in doubt. The rule would be a fault only if it said true for a host that is not this machine.

Field notes

  • This scanner counts every failure as "closed". A real tool separates "refused" (closed), "timeout" (filtered, or the host is down) and errors such as too many open files. Otherwise a low ulimit -n gives a report with missing ports and no warning.
  • The worst-case time of a scan is about ports / workers * timeout. For 1,024 ports, 100 workers and a 500 ms timeout, that is 1024 / 100 * 0.5 s, about 5 s. Too many workers can trip the alarms of your own network.
  • Scan returns a partial list together with the context error. A caller that ignores the error would treat a stopped scan as a finished one, so lesson 9 prints nothing in that case.
  • A test that opens its own listener is repeatable and touches nothing else. Do not point a test at a host that you do not control, even to see a "closed" result.