Skip to main content

Get IP Address

Description

The get_ip_address function retrieves the IP address associated with the local machine's hostname. If an error occurs while fetching the IP address, it returns a default IP address "0.0.0.0".

Function Signature:

def get_ip_address() -> str:

Parameters

This function does not take any parameters.

Returns

  • str: The IP address of the local machine. If an error occurs, the function returns the default IP address "0.0.0.0".

Example Usage

Here’s an example of how the function works:

ip_address = get_ip_address()
print(ip_address)

Example Output:

192.168.1.5

Code

import socket

def get_ip_address() -> str:
try:
# Get the local hostname
hostname = socket.gethostname()
# Get the IP address associated with the hostname
ip_address = socket.gethostbyname(hostname)
except socket.error:
# If an error occurs, return a default IP address
ip_address = "0.0.0.0"

return ip_address

Errors and Exceptions

  • If an error occurs during the process of getting the hostname or IP address, a socket.error will be caught and the function will return "0.0.0.0" as the fallback IP address.

Notes

This function is commonly used to obtain the local IP address of the machine. It can be useful for network-related tasks, such as when the application needs to identify itself on the local network.