hbutils.system.network.hosts

Host file utilities for cross-platform systems.

This module provides small utilities for locating and parsing the system hosts file. It offers functions to resolve the hosts file path according to the current operating system, parse host entries into a dictionary, and retrieve the IP address of localhost. The implementation supports Windows and Unix-like platforms.

The module contains the following main components:

  • hostfile() - Resolve the hosts file path for the current OS

  • get_hosts() - Parse the hosts file into a hostname-to-IP mapping

  • get_localhost_ip() - Retrieve the IP address associated with localhost

Example:

>>> from hbutils.system.network.hosts import hostfile, get_hosts, get_localhost_ip
>>> hostfile()  
'/etc/hosts'
>>> hosts = get_hosts()  
>>> hosts.get('localhost')  
'127.0.0.1'
>>> get_localhost_ip()  
'127.0.0.1'

Note

Parsing ignores empty lines and comments in the hosts file.

__all__

hbutils.system.network.hosts.__all__ = ['hostfile', 'get_hosts', 'get_localhost_ip']

Built-in mutable sequence.

If no argument is given, the constructor creates a new empty list. The argument must be an iterable if specified.

hostfile

hbutils.system.network.hosts.hostfile() str[source]

Get the hosts file path for the current operating system.

Returns:

Hosts file path on this operating system.

Return type:

str

Note

This should be /etc/hosts on Linux and macOS, and c:\windows\system32\drivers\etc\hosts on Windows.

Examples::
>>> from hbutils.system.network.hosts import hostfile
>>> hostfile()  # On Linux/macOS  
'/etc/hosts'
>>> hostfile()  # On Windows  
'c:\\windows\\system32\\drivers\\etc\\hosts'

get_hosts

hbutils.system.network.hosts.get_hosts() Dict[str, str][source]

Parse the system hosts file into a dictionary.

This function reads the system hosts file line-by-line and constructs a mapping from each hostname to its associated IP address. Inline comments (starting with #) and blank lines are ignored.

Returns:

Dictionary mapping hostnames to their corresponding IP addresses.

Return type:

Dict[str, str]

Examples::
>>> from hbutils.system.network.hosts import get_hosts
>>> get_hosts()  
{'hansbug-VirtualBox': '127.0.0.1', 'localhost': '127.0.0.1'}

get_localhost_ip

hbutils.system.network.hosts.get_localhost_ip() str[source]

Get the IP address of localhost.

This function retrieves the IP address associated with localhost from the system hosts file. If localhost is not present, it returns the default value 127.0.0.1.

Returns:

IP address of localhost.

Return type:

str

Examples::
>>> from hbutils.system.network.hosts import get_localhost_ip
>>> get_localhost_ip()  
'127.0.0.1'