Parsing endpoints, including IPv6

Host and port pairs

Lesson 10 of 20 · 10 min · Module 3: Ports and endpoints

Configuration files and logs write endpoints as host:port. IPv6 addresses already contain colons, so they are wrapped in brackets: [2001:db8::1]:443.

Start this lesson →

Free. No installation: you write and run the code in your browser, and it is checked automatically.

By the end, you’ll be able to…

  • Split text at the last separator
  • Handle the IPv6 bracket notation
  • Validate a port while parsing

The idea

text.rpartition(":") splits at the last colon, returning (before, ":", after). For bracketed IPv6, find the closing ] first. Convert the port with int() and check its range.

print("example.com:443".rpartition(":"))

01Why the last colon

In example.com:443 there is only one colon, but a split at the last one also works for formats that contain earlier colons. rpartition always returns three parts, so it never raises.

print("db-01".rpartition(":"))
Output
('', '', 'db-01')

02Brackets protect IPv6

2001:db8::1:8443 is ambiguous: is 8443 the port or part of the address? Brackets remove the doubt, which is why URLs and configs write [2001:db8::1]:8443.

03Validate at the boundary

Parsing is the moment text from outside enters your program. Rejecting "web:http" or "web:70000" there prevents confusing errors much later.

Your turn

Write parse_endpoint(text, default_port=80) returning a (host, port) tuple. Support host:port, host alone (use the default port), [ipv6]:port, and [ipv6]. Return the IPv6 host without brackets. Raise ValueError for a port that is not a number from 1 to 65535.

What the checks look for

  • Parses host:port
  • Uses the default port when none is given
  • Handles bracketed IPv6
  • Rejects invalid ports
Try it in the editor →

Take this with you

Use brackets to find IPv6 hosts and the last colon for everything else.

Go a little further

Accept a scheme prefix such as tcp:// or udp:// and return it as a third value.

Learn Networking Foundations for free

20 short lessons with real code and instant checks.

See the whole course →