Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- #include <string.h>
- #include <unistd.h>
- #include <fcntl.h>
- #include <sys/ioctl.h>
- #include <net/if.h>
- #include <linux/if_tun.h>
- #include <arpa/inet.h>
- #include <pthread.h>
- #define BUFSIZE 2000
- int make_tun(char const *dev) {
- struct ifreq ifr;
- int fd, err;
- if ((fd = open("/dev/net/tun", O_RDWR)) < 0) {
- perror("Opening /dev/net/tun");
- exit(EXIT_FAILURE);
- }
- memset(&ifr, 0, sizeof(ifr));
- ifr.ifr_flags = IFF_TUN | IFF_NO_PI;
- if (*dev)
- strncpy(ifr.ifr_name, dev, IFNAMSIZ);
- if ((err = ioctl(fd, TUNSETIFF, (void *)&ifr)) < 0) {
- perror("ioctl(TUNSETIFF)");
- close(fd);
- exit(err);
- }
- return fd;
- }
- int setup_tun(char const *ns, char const *dev, char const *ip) {
- char command[200];
- char const *cmds[] = {
- "ip netns add %s",
- "ip netns exec %s ip link set dev lo up",
- "ip link set netns %s dev %s",
- "ip netns exec %s ip addr add dev %s %s",
- "ip netns exec %s ip link set dev %s up",
- 0
- };
- char const * const *cmd;
- int fd = make_tun(dev);
- for (cmd=cmds; *cmd; ++cmd) {
- snprintf(command, sizeof(command), *cmd, ns, dev, ip);
- int ret = system(command);
- printf("'%s' returned %d\n", command, ret);
- }
- return fd;
- }
- void forward_traffic(int src_fd, int dest_fd) {
- char buf[BUFSIZE];
- ssize_t nbytes = 0;
- while (nbytes >= 0) {
- nbytes = read(src_fd, buf, sizeof(buf));
- if (nbytes >= 0) {
- usleep(nbytes);
- nbytes = write(dest_fd, buf, nbytes);
- }
- }
- perror("Read/write TUN device");
- exit(EXIT_FAILURE);
- }
- void *thread_function(void *arg) {
- int *fds = (int *)arg;
- forward_traffic(fds[0], fds[1]);
- return NULL;
- }
- int main() {
- int tun_fd1, tun_fd2;
- pthread_t tid1, tid2;
- int fds1[2], fds2[2];
- tun_fd1 = setup_tun("test1", "tun0", "10.0.0.1/24");
- tun_fd2 = setup_tun("test2", "tun1", "10.0.0.2/24");
- fds1[0] = tun_fd1;
- fds1[1] = tun_fd2;
- fds2[0] = tun_fd2;
- fds2[1] = tun_fd1;
- pthread_create(&tid1, NULL, thread_function, (void *)fds1);
- pthread_create(&tid2, NULL, thread_function, (void *)fds2);
- pthread_join(tid1, NULL);
- pthread_join(tid2, NULL);
- close(tun_fd1);
- close(tun_fd2);
- return EXIT_SUCCESS;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement