summaryrefslogtreecommitdiff
path: root/linuxnamespaces
diff options
context:
space:
mode:
authorHelmut Grohne <helmut@subdivi.de>2024-06-22 08:17:16 +0200
committerHelmut Grohne <helmut@subdivi.de>2024-06-22 08:17:16 +0200
commit0cf893c21b5da2deecad7bf7723a607de7ef4233 (patch)
treec000e10a06639aa2619ddc61b292d649ac650575 /linuxnamespaces
parentd6696df84c0c25e597edb5aa58c863ef360213d3 (diff)
downloadpython-linuxnamespaces-0cf893c21b5da2deecad7bf7723a607de7ef4233.tar.gz
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.
Diffstat (limited to 'linuxnamespaces')
-rw-r--r--linuxnamespaces/__init__.py17
1 files changed, 17 insertions, 0 deletions
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))