Python's standard library includes a module named socket that provides low-level network interface support, including functionalities such as retrieving hostnames and IP addresses.
Here is an example of using the socket module to retrieve the local IP address:
pythonimport socket def get_local_ip(): try: # Create a socket object s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) # Attempt to connect to a non-existent address s.connect(("10.255.255.255", 1)) # Retrieve the local IP address IP = s.getsockname()[0] except Exception as e: print(f"Cannot retrieve IP address: {e}") IP = "127.0.0.1" finally: # Close the socket s.close() return IP # Retrieve and print the local IP address local_ip = get_local_ip() print(f"Local IP address is: {local_ip}")
In this example, we first create a UDP socket (since UDP does not require establishing a connection like TCP, enabling a more efficient retrieval of the IP address). Then, we attempt to connect to an address that typically does not exist (the IP address '10.255.255.255' is a broadcast address, and port 1 is an arbitrary choice). This operation forces the operating system to select a valid local IP address for sending packets, even though the packets are not actually transmitted. Subsequently, we retrieve the local IP address bound to this socket by calling the getsockname() method.
Finally, we ensure the socket is closed after the operation and handle potential exceptions to maintain the program's robustness.
One key advantage of this method is that it typically returns the IP address used for external communication, rather than just localhost (127.0.0.1). However, this approach may encounter issues in certain special network configurations, such as when the system uses multiple network interfaces. In such cases, it may be necessary to combine this method with other approaches, such as querying the system's network configuration.