Skip to content

Instantly share code, notes, and snippets.

@proelbtn
Last active June 25, 2022 03:20
Show Gist options
  • Save proelbtn/824cf638d38b85cfc16227e07cceca78 to your computer and use it in GitHub Desktop.
Save proelbtn/824cf638d38b85cfc16227e07cceca78 to your computer and use it in GitHub Desktop.
#define _GNU_SOURCE
#include <fcntl.h>
#include <sched.h>
#include <stdio.h>
#include <stdlib.h>
int main(int argc, const char *argv[]) {
if (argc != 3) {
printf("Usage:\n");
printf("\t%s NETNS_FILE COMMAND\n", argv[0]);
return 1;
}
int fd = open(argv[1], 0);
if (fd < 0) {
printf("Cloudn't open netns file\n");
return 1;
}
int err = setns(fd, CLONE_NEWNET);
if (err != 0) {
printf("Failed to setns\n");
return 1;
}
system(argv[2]);
}
$ sudo ./a.out /proc/1/ns/net "cat /proc/net/dev"
Inter-| Receive | Transmit
face |bytes packets errs drop fifo frame compressed multicast|bytes packets errs drop fifo colls carrier compressed
lo: 19169789308 3292433 0 0 0 0 0 0 19169789308 3292433 0 0 0 0 0 0
enp3s0: 54061868186 93390689 0 1601 0 0 0 193967 52834018320 90656143 0 0 0 0 0 0
wlp2s0: 4710068 25551 0 0 0 0 0 0 28146620 31022 0 0 0 0 0 0
Management: 4339712 25470 0 0 0 0 0 0 4130 7 0 0 0 0 0 0
private: 11043357669 30494619 0 0 0 0 0 1070 38382690789 44373108 0 0 0 0 0 0
external: 39295920892 47042469 0 163965 0 0 0 164002 11910273444 32507959 0 0 0 0 0 0
br-a108010ddf73: 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
docker0: 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
guest: 116642051 161708 0 0 0 0 0 1434 482205883 357946 0 0 0 0 0 0
dmz: 325641255 1741815 0 0 0 0 0 0 828399876 1301762 0 0 0 0 0 0
$ sudo ./a.out /proc/110156/ns/net "cat /proc/net/dev"
[sudo] password for proelbtn:
Inter-| Receive | Transmit
face |bytes packets errs drop fifo frame compressed multicast|bytes packets errs drop fifo colls carrier compressed
lo: 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
$ sudo ./a.out "/run/netns/test" "cat /proc/net/dev"
Inter-| Receive | Transmit
face |bytes packets errs drop fifo frame compressed multicast|bytes packets errs drop fifo colls carrier compressed
lo: 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment