In Python, to verify if a device has an active network connection, multiple methods can be employed. Here, I will introduce two commonly used approaches:
Method One: Using the socket Library
You can utilize the socket library to establish a connection, for example, by connecting to a common address such as Google's homepage. If the connection succeeds, it confirms an active network connection.
pythonimport socket def check_network_connection(host="8.8.8.8", port=53, timeout=3): """ Verify network connectivity :param host: The remote IP address to connect to, defaulting to Google's DNS server :param port: The port number, defaulting to the DNS service port :param timeout: Connection timeout duration :return: Boolean value, returning True if the connection succeeds, otherwise False """ try: socket.setdefaulttimeout(timeout) socket.socket(socket.AF_INET, socket.SOCK_STREAM).connect((host, port)) return True except socket.error as ex: print(f"Connection error: {ex}") return False # Example usage if check_network_connection(): print("Network connection is active!") else: print("No network connection.")
Method Two: Using the requests Library
Another approach is to use the requests library to attempt accessing a website (e.g., www.google.com). If the request succeeds, the network connection is active.
pythonimport requests def check_internet(url='http://www.google.com', timeout=5): """ Verify internet connectivity via HTTP request :param url: The URL to test connectivity to, defaulting to Google's homepage :param timeout: Request timeout duration :return: Boolean value, returning True if the request succeeds, otherwise False """ try: response = requests.get(url, timeout=timeout) # Verify HTTP response status code is 200 return response.status_code == 200 except requests.ConnectionError: print("Unable to connect to the internet") return False except requests.Timeout: print("Connection timeout") return False except requests.RequestException as e: print(f"Request error: {e}") return False # Example usage if check_internet(): print("Network connection is active!") else: print("No network connection.")
Summary
Both methods have distinct advantages and disadvantages. The socket library approach is more low-level and efficiently verifies network connectivity, while the requests library provides higher-level HTTP operations that enable detailed simulation of network requests, including handling redirects and SSL. Select the appropriate method based on your specific application requirements.