lima-vm/lima · error

unexpected port %d

Error message

unexpected port %d

What it means

After successfully asserting the listener address is a *net.TCPAddr, TCP() verifies the kernel-assigned port is positive. A port <= 0 means the OS handed back an unusable port number, so the library refuses to return it. This is another invariant check on the kernel's port allocator.

Source

Thrown at pkg/freeport/freeport.go:29

func TCP() (int, error) {
	lAddr0, err := net.ResolveTCPAddr("tcp4", "127.0.0.1:0")
	if err != nil {
		return 0, err
	}
	l, err := net.ListenTCP("tcp4", lAddr0)
	if err != nil {
		return 0, err
	}
	defer l.Close()
	lAddr := l.Addr()
	lTCPAddr, ok := lAddr.(*net.TCPAddr)
	if !ok {
		return 0, fmt.Errorf("expected *net.TCPAddr, got %v", lAddr)
	}
	port := lTCPAddr.Port
	if port <= 0 {
		return 0, fmt.Errorf("unexpected port %d", port)
	}
	return port, nil
}

func UDP() (int, error) {
	lAddr0, err := net.ResolveUDPAddr("udp4", "127.0.0.1:0")
	if err != nil {
		return 0, err
	}
	l, err := net.ListenUDP("udp4", lAddr0)
	if err != nil {
		return 0, err
	}
	defer l.Close()
	lAddr := l.LocalAddr()
	lUDPAddr, ok := lAddr.(*net.UDPAddr)
	if !ok {
		return 0, fmt.Errorf("expected *net.UDPAddr, got %v", lAddr)

View on GitHub (pinned to dd909d0973)

Solutions

  1. Retry the call; port allocation failures are often transient.
  2. Verify the host's ephemeral port range is sane (e.g. net.ipv4.ip_local_port_range on Linux).
  3. Check container/sandbox network configuration; restart the networking stack or the container.
  4. If persistent, report with OS/kernel details as this indicates a port-allocation defect.
Defensive patterns

Strategy: retry

Try / catch

var port int
var err error
for i := 0; i < 3; i++ {
    port, err = freeport.TCP()
    if err == nil { break }
    time.Sleep(100 * time.Millisecond)
}
if err != nil { return fmt.Errorf("port allocation failed after retries: %w", err) }

Prevention

When it happens

Trigger: Calling freeport.TCP() when the OS assigns port 0 or a negative port in the *net.TCPAddr result — e.g. a kernel/container network bug or an environment where ephemeral port allocation is broken.

Common situations: Container/sandbox environments with broken networking, heavily constrained CI runners, or OS-level misconfiguration of the ephemeral port range.

Related errors


AI-assisted analysis of lima-vm/lima@dd909d0973 (2026-09-01). Data as JSON: /api/errors/45409c5586ed956d. Report an issue: GitHub.