From 0cf893c21b5da2deecad7bf7723a607de7ef4233 Mon Sep 17 00:00:00 2001 From: Helmut Grohne Date: Sat, 22 Jun 2024 08:17:16 +0200 Subject: add function enable_loopback_if It can be used in a new network namespace to enable the loopback network interface and thus provide easy network isolation. --- linuxnamespaces/__init__.py | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/linuxnamespaces/__init__.py b/linuxnamespaces/__init__.py index 1b4ca07..0af6dee 100644 --- a/linuxnamespaces/__init__.py +++ b/linuxnamespaces/__init__.py @@ -10,9 +10,12 @@ import bisect import contextlib import dataclasses import errno +import fcntl import os import pathlib +import socket import stat +import struct import subprocess import typing @@ -787,3 +790,17 @@ def async_waitpidfd( async variant of waitid(P_PIDFD, pidfd, flags). """ return _AsyncPidfdWaiter(pidfd, flags).fut + + +def enable_loopback_if() -> None: + """Enable the loopback network interface that is initially down in a new + network namespace. + """ + # We us the old and deprecated ioctl API rather than netlink, because it + # is way simpler and good enough for our purpose. The interface is always + # created as "lo" by the kernel and it'll have loopback addresses + # configured automatically. All that we have to do is "up" it. + SIOCSIFFLAGS = 0x8914 + IFF_UP = 1 + with socket.socket(socket.AF_INET, socket.SOCK_DGRAM, 0) as sock: + fcntl.ioctl(sock, SIOCSIFFLAGS, struct.pack("@16sH", b"lo", IFF_UP)) -- cgit v1.2.3