PyObjC SystemConfiguration Framework

12.1 · active · verified Tue Apr 14

PyObjC provides Python bindings for macOS frameworks. This specific package wraps the SystemConfiguration.framework, allowing Python applications to interact with system network settings, reachability, and other system configuration details. It is actively developed, with version 12.1 being the current stable release, and follows a release cadence tied to macOS SDK updates and Python version support.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to use `SystemConfiguration` to check if the network is generally reachable. It uses `SCNetworkReachabilityCreateWithName` and `SCNetworkReachabilityGetFlags` to query the system's network status. Note that this check primarily indicates local network connectivity, not necessarily internet access. For full functionality, you would often interact with `SCDynamicStore` for more detailed network state.

import SystemConfiguration
import socket

def is_network_reachable():
    # Check if network is generally reachable (e.g., Wi-Fi or Ethernet connected)
    # This is a basic check and doesn't verify internet access.

    # Create a socket address for 0.0.0.0 (any address)
    zero_address = ('0.0.0.0', 0)
    target_address = SystemConfiguration.SCNetworkReachabilityCreateWithName(None, zero_address[0])

    if not target_address:
        print("Failed to create reachability reference.")
        return False

    # Get the reachability flags
    # The 'flags' variable will be an NSInteger, which behaves like a Python int
    is_reachable, flags = SystemConfiguration.SCNetworkReachabilityGetFlags(target_address, None)

    if not is_reachable:
        return False

    # Define common reachability flags
    kSCNetworkReachabilityFlagsReachable = 1 << 1 # Network is reachable
    kSCNetworkReachabilityFlagsConnectionRequired = 1 << 2 # Connection must be established first
    kSCNetworkReachabilityFlagsTransientConnection = 1 << 3 # Connection will go away, use only for setup
    kSCNetworkReachabilityFlagsIsWWAN = 1 << 17 # Connection is a WWAN connection
    kSCNetworkReachabilityFlagsIsDirect = 1 << 4 # Direct connection to the target host

    # Check if the 'Reachable' flag is set and 'ConnectionRequired' is not set
    if (flags & kSCNetworkReachabilityFlagsReachable) and \
       not (flags & kSCNetworkReachabilityFlagsConnectionRequired):
        return True
    return False

if __name__ == '__main__':
    if is_network_reachable():
        print("Network is reachable.")
    else:
        print("Network is not reachable (or requires connection).")

view raw JSON →