PyObjC CFNetwork Framework Bindings
PyObjC provides Python bindings for Apple's macOS frameworks, allowing Python applications to interact with Objective-C APIs. The `pyobjc-framework-cfnetwork` package specifically provides wrappers for the CFNetwork framework, which offers a C-based API for low-level network services. It is actively maintained as part of the broader PyObjC project, with releases often coinciding with new macOS SDK updates and Python version support. The current version is 12.1.
Warnings
- breaking Python 3.9 support was dropped in PyObjC 12.0. Python 3.8 support was dropped in PyObjC 11.0.
- breaking PyObjC 11.1 introduced changes to correctly model Automatic Reference Counting (ARC) for initializer methods (e.g., methods in the 'init' family). This aligns with `clang`'s documentation, where initializers steal a reference to `self` and return a new one.
- gotcha Experimental support for free-threading (PEP 703) in Python 3.13 and later is *not yet fully supported* or stable in PyObjC, despite PyObjC 11.0 introducing *experimental* changes related to it.
- gotcha The behavior of `__init__` when a custom `__new__` is implemented changed in PyObjC 10.3, potentially breaking existing code. While 10.3.1 partially re-introduced `__init__` support for classes with user-implemented `__new__`, those relying on PyObjC's `__new__` still cannot use `__init__`.
- breaking PyObjC 10.0 removed bindings for the `IMServicePlugIn` framework, as it was deprecated in macOS 10.13 and removed in macOS 14.
Install
-
pip install pyobjc-framework-cfnetwork
Imports
- CFNetwork
import CFNetwork
Quickstart
import CFNetwork
# Create a CFHost object for a given hostname
hostname = "www.apple.com"
host = CFNetwork.CFHostCreateWithName(None, hostname)
if host:
# Start info resolution (blocking for simplicity; real apps might use async)
# kCFHostAddresses resolves IP addresses
success = CFNetwork.CFHostStartInfoResolution(
host, CFNetwork.kCFHostAddresses, None
)
if success:
# Retrieve the resolved addresses
# PyObjC automatically converts CFArrayRef to Python list
addresses = CFNetwork.CFHostGetAddressing(host, None)
if addresses:
print(f"Resolved addresses for {hostname}:")
for address in addresses:
# address is a CFDataRef containing sockaddr_storage
print(f" {address}")
else:
print(f"No addresses found for {hostname}")
else:
print(f"Failed to resolve host {hostname}")
# Stop resolution and release resources (PyObjC handles Python object lifecycle)
CFNetwork.CFHostStopInfoResolution(host)
else:
print(f"Failed to create CFHost object for {hostname}")