Back to home page

OSCL-LXR

 
 

    


0001 // SPDX-License-Identifier: GPL-2.0
0002 #define _GNU_SOURCE
0003 #include <sched.h>
0004 #include <unistd.h>
0005 #include <stdio.h>
0006 #include <errno.h>
0007 #include <string.h>
0008 #include <stdlib.h>
0009 #include <stdint.h>
0010 #include <sys/types.h>
0011 #include <sys/socket.h>
0012 
0013 #ifndef SO_NETNS_COOKIE
0014 #define SO_NETNS_COOKIE 71
0015 #endif
0016 
0017 #define pr_err(fmt, ...) \
0018     ({ \
0019         fprintf(stderr, "%s:%d:" fmt ": %m\n", \
0020             __func__, __LINE__, ##__VA_ARGS__); \
0021         1; \
0022     })
0023 
0024 int main(int argc, char *argvp[])
0025 {
0026     uint64_t cookie1, cookie2;
0027     socklen_t vallen;
0028     int sock1, sock2;
0029 
0030     sock1 = socket(AF_INET, SOCK_STREAM, 0);
0031     if (sock1 < 0)
0032         return pr_err("Unable to create TCP socket");
0033 
0034     vallen = sizeof(cookie1);
0035     if (getsockopt(sock1, SOL_SOCKET, SO_NETNS_COOKIE, &cookie1, &vallen) != 0)
0036         return pr_err("getsockopt(SOL_SOCKET, SO_NETNS_COOKIE)");
0037 
0038     if (!cookie1)
0039         return pr_err("SO_NETNS_COOKIE returned zero cookie");
0040 
0041     if (unshare(CLONE_NEWNET))
0042         return pr_err("unshare");
0043 
0044     sock2 = socket(AF_INET, SOCK_STREAM, 0);
0045     if (sock2 < 0)
0046         return pr_err("Unable to create TCP socket");
0047 
0048     vallen = sizeof(cookie2);
0049     if (getsockopt(sock2, SOL_SOCKET, SO_NETNS_COOKIE, &cookie2, &vallen) != 0)
0050         return pr_err("getsockopt(SOL_SOCKET, SO_NETNS_COOKIE)");
0051 
0052     if (!cookie2)
0053         return pr_err("SO_NETNS_COOKIE returned zero cookie");
0054 
0055     if (cookie1 == cookie2)
0056         return pr_err("SO_NETNS_COOKIE returned identical cookies for distinct ns");
0057 
0058     close(sock1);
0059     close(sock2);
0060     return 0;
0061 }