sgl-project/sglang · error · ValueError

Invalid port number: {s!r}

Error message

Invalid port number: {s!r}

What it means

The NetworkAddress parser's _parse_port converts the port substring to int; a non-numeric token (empty string, hostname fragment, 'auto', trailing colon) raises ValueError with the offending string shown via !r.

Source

Thrown at python/sglang/srt/utils/network.py:445

def _is_ipv6(host: str) -> bool:
    """Check whether *host* is a valid IPv6 address (without brackets)."""
    try:
        ipaddress.IPv6Address(host)
        return True
    except ValueError:
        return False


def _wrap(host: str) -> str:
    """Wrap an IPv6 address in brackets; pass IPv4/hostname through."""
    return f"[{host}]" if _is_ipv6(host) else host


def _parse_port(s: str) -> int:
    try:
        port = int(s)
    except ValueError:
        raise ValueError(f"Invalid port number: {s!r}")
    if not (0 <= port <= 65535):
        raise ValueError(f"Port out of range (0-65535): {port}")
    return port


@dataclass(frozen=True)
class NetworkAddress:
    host: str
    port: int

    def __post_init__(self):
        # Auto-strip IPv6 brackets so callers can pass "[::1]" or "::1"
        if self.host.startswith("[") and self.host.endswith("]"):
            object.__setattr__(self, "host", self.host[1:-1])

    @property
    def is_ipv6(self) -> bool:
        return _is_ipv6(self.host)

View on GitHub (pinned to 0132848349)

Solutions

  1. Fix the endpoint string to have a numeric port (host:8000).
  2. Validate env-derived endpoint strings before parsing.
  3. If the port is optional, split and default it before calling parse.

Example fix

# before
addr = NetworkAddress.parse(f"{host}:{port_var}")  # port_var=None -> "host:None"

# after
port_var = port_var or 8000
addr = NetworkAddress.parse(f"{host}:{port_var}")
Defensive patterns

Strategy: validation

Validate before calling

def valid_port_str(s: str) -> bool:
    return s.isdigit() and len(s) <= 5

Try / catch

try:
    addr = NetworkAddress.parse(endpoint)
except ValueError as e:
    raise SystemExit(f"bad endpoint {endpoint!r}: {e}") from e

Prevention

When it happens

Trigger: NetworkAddress.parse("host:abc"), parse("host:"), or an endpoint string like "0.0.0.0:auto" where a non-integer appears where the port must be.

Common situations: Config values templated with unset variables producing empty ports; endpoints built by string concatenation where the port piece is optional/None rendered as 'None'.

Related errors


AI-assisted analysis of sgl-project/sglang@0132848349 (2026-08-28). Data as JSON: /api/errors/63fbc92b7539629e. Report an issue: GitHub.