Add support for attaching to network namespace using setns(2)
This commit is contained in:
@@ -14,6 +14,9 @@
|
|||||||
#include <stdio.h>
|
#include <stdio.h>
|
||||||
#include <linux/sched.h>
|
#include <linux/sched.h>
|
||||||
#include <unistd.h>
|
#include <unistd.h>
|
||||||
|
#include <limits.h>
|
||||||
|
#include <syscall.h>
|
||||||
|
#include <fcntl.h>
|
||||||
|
|
||||||
void usage(char *name)
|
void usage(char *name)
|
||||||
{
|
{
|
||||||
@@ -22,15 +25,26 @@ void usage(char *name)
|
|||||||
"-c: close all file descriptors except stdin/out/error\n"
|
"-c: close all file descriptors except stdin/out/error\n"
|
||||||
"-d: detach from tty by calling setsid()\n"
|
"-d: detach from tty by calling setsid()\n"
|
||||||
"-n: run in new network namespace\n"
|
"-n: run in new network namespace\n"
|
||||||
"-p: print ^A + pid\n", name);
|
"-p: print ^A + pid\n"
|
||||||
|
"-a pid: attach to pid's network namespace\n",
|
||||||
|
name);
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
int setns(int fd, int nstype)
|
||||||
|
{
|
||||||
|
return syscall(308, fd, nstype);
|
||||||
}
|
}
|
||||||
|
|
||||||
int main(int argc, char *argv[])
|
int main(int argc, char *argv[])
|
||||||
{
|
{
|
||||||
char c;
|
char c;
|
||||||
int fd;
|
int fd;
|
||||||
|
char path[PATH_MAX];
|
||||||
while ((c = getopt(argc, argv, "+cdnp")) != -1)
|
int nsid;
|
||||||
|
int pid;
|
||||||
|
|
||||||
|
while ((c = getopt(argc, argv, "+cdnpa:")) != -1)
|
||||||
switch(c) {
|
switch(c) {
|
||||||
case 'c':
|
case 'c':
|
||||||
/* close file descriptors except stdin/out/error */
|
/* close file descriptors except stdin/out/error */
|
||||||
@@ -64,6 +78,20 @@ int main(int argc, char *argv[])
|
|||||||
printf("\001%d\n", getpid());
|
printf("\001%d\n", getpid());
|
||||||
fflush(stdout);
|
fflush(stdout);
|
||||||
break;
|
break;
|
||||||
|
case 'a':
|
||||||
|
/* Attach to pid's network namespace */
|
||||||
|
pid = atoi(optarg);
|
||||||
|
sprintf(path, "/proc/%d/ns/net", pid );
|
||||||
|
nsid = open(path, O_RDONLY);
|
||||||
|
if (nsid < 0) {
|
||||||
|
perror(path);
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
if (setns(nsid, 0) != 0) {
|
||||||
|
perror("setns");
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
break;
|
||||||
default:
|
default:
|
||||||
usage(argv[0]);
|
usage(argv[0]);
|
||||||
break;
|
break;
|
||||||
|
|||||||
Reference in New Issue
Block a user