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 OSget_hosts()- Parse the hosts file into a hostname-to-IP mappingget_localhost_ip()- Retrieve the IP address associated withlocalhost
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/hostson Linux and macOS, andc:\windows\system32\drivers\etc\hostson 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
localhostfrom the system hosts file. Iflocalhostis not present, it returns the default value127.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'