Parsing configuration text

Read a hosts file

Lesson 12 of 20 · 9 min · Module 4: Names and the web

Before asking DNS, a computer checks its local hosts file. Each line maps an IP address to one or more names.

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…

  • Read a simple configuration format
  • Strip comments and whitespace
  • Resolve duplicates deliberately

The idea

A hosts line looks like 192.168.1.10 web-01 web: an address, then names separated by spaces or tabs. Everything after # is a comment. line.split() with no arguments splits on any run of whitespace.

line = "192.168.1.10   web-01 web  # main web server"
print(line.split("#", 1)[0].split())

01Comments first

Removing everything after # before splitting means a comment can never be mistaken for a host name. split("#", 1) splits at most once.

02split() handles messy spacing

Hosts files often mix spaces and tabs to line up columns. split() with no argument treats any run of whitespace as one separator and ignores leading and trailing spaces.

print("  10.0.0.5\t db  ".split())
Output
['10.0.0.5', 'db']

03First match wins

Resolvers read the file from top to bottom and stop at the first match. setdefault mirrors that behaviour: it never overwrites an existing name.

Your turn

Write parse_hosts(text) that returns a dict mapping every name to its IP address. Ignore comments and blank lines. If a name appears more than once, keep the first address, as the system resolver does.

What the checks look for

  • Maps several names on one line
  • Ignores comments, blank lines and tabs
  • Keeps the first address for a repeated name
  • Skips lines with only an address
Try it in the editor →

Take this with you

Clean the line, split it, then map every alias to its address.

Go a little further

Reject lines whose address is not a valid IP address, using the ipaddress module.

Learn Networking Foundations for free

20 short lessons with real code and instant checks.

See the whole course →