]> git.ipfire.org Git - thirdparty/iproute2.git/commitdiff
namespace: Add fallback to netns by pid
authorDavid Ahern <dahern@nvidia.com>
Tue, 12 May 2026 19:26:03 +0000 (13:26 -0600)
committerDavid Ahern <dsahern@kernel.org>
Fri, 15 May 2026 19:22:35 +0000 (13:22 -0600)
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 <dahern@nvidia.com>
Reviewed-by: Leon Romanovsky <leonro@nvidia.com>
Signed-off-by: David Ahern <dsahern@kernel.org>
lib/namespace.c

index 74b7e7caf0e5b2dd3794a1e26f03218ac420c037..0bba3a163563ef6064e3f1b14411dd0bd244383c 100644 (file)
@@ -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)