Subject: [PATCH iproute2-next v2 1/4] namespace: Add fallback to netns by pid

From: David Ahern <[email-masked]>
Date: Tue, 12 May 2026 13:34:04 -0600

From: David Ahern <[email-masked]>

Update netns_get_fd to try the passed in string as a name first. If the
netns filesystem entry does not exist, try converting the string to an
integer and if successful return an fd to /proc/<pid>/ns/net.

This allows netns_get_fd to uniformly handle the 2 common use cases of
specifying network namespace by name and pid.

Signed-off-by: David Ahern <[email-masked]>
---
 lib/namespace.c | 28 +++++++++++++++++++++-------
 1 file changed, 21 insertions(+), 7 deletions(-)

diff --git a/lib/namespace.c b/lib/namespace.c
index 74b7e7caf0e5..0bba3a163563 100644
--- a/lib/namespace.c
+++ b/lib/namespace.c
@@ -99,19 +99,33 @@ int netns_switch(char *name)
 	return 0;
 }
 
-int netns_get_fd(const char *name)
+/* try str as the name of the namespace first, then
+ * fallback to pid
+ */
+int netns_get_fd(const char *str)
 {
 	char pathbuf[PATH_MAX];
-	const char *path, *ptr;
+	const char *path;
+	int pid;
+	int fd;
 
-	path = name;
-	ptr = strchr(name, '/');
-	if (!ptr) {
+	path = str;
+	if (!strchr(str, '/')) {
 		snprintf(pathbuf, sizeof(pathbuf), "%s/%s",
-			NETNS_RUN_DIR, name );
+			NETNS_RUN_DIR, str);
 		path = pathbuf;
 	}
-	return open(path, O_RDONLY);
+
+	fd = open(path, O_RDONLY);
+	if (fd >= 0)
+		return fd;
+
+	/* make sure string is an integer */
+	if (get_integer(&pid, str, 0) < 0)
+		return -1;
+
+	snprintf(pathbuf, sizeof(pathbuf), "/proc/%s/ns/net", str);
+	return open(pathbuf, O_RDONLY);
 }
 
 int netns_foreach(int (*func)(char *nsname, void *arg), void *arg)
-- 
2.43.0