Created
June 25, 2015 22:00
-
-
Save pbiernacki/81eba3889d7917e9d178 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <sys/types.h> | |
#include <sys/ioctl.h> | |
#include <sys/socket.h> | |
#include <sys/sockio.h> | |
#include <sys/stat.h> | |
#include <arpa/inet.h> | |
#include <net/if.h> | |
#include <net/if_tap.h> | |
#include <netinet/in.h> | |
#include <err.h> | |
#include <fcntl.h> | |
#include <stdio.h> | |
#include <stdlib.h> | |
#include <string.h> | |
#include <unistd.h> | |
int | |
main(int argc, const char *argv[]) | |
{ | |
int dev; | |
if ((dev = open("/dev/tap", O_RDWR)) == -1) | |
err(1, "open()"); | |
char *name = fdevname(dev); | |
printf("opened %s\n", name); | |
int sock; | |
if ((sock = socket(AF_INET, SOCK_DGRAM, 0)) == -1) | |
err(1, "socket()"); | |
struct ifreq ifr; | |
strlcpy(ifr.ifr_name, name, IFNAMSIZ); | |
if (ioctl(sock, SIOCGIFMTU, &ifr) == -1) | |
err(1, "ioctl(SIOCGIFMTU)"); | |
printf("mtu: %d\n", ifr.ifr_mtu); | |
struct ifaliasreq ifa; | |
strlcpy(ifa.ifra_name, name, IFNAMSIZ); | |
#define SIN(_sa) (*(struct sockaddr_in *)&(_sa)) | |
SIN(ifa.ifra_addr).sin_len = sizeof(struct sockaddr_in); | |
SIN(ifa.ifra_addr).sin_family = AF_INET; | |
SIN(ifa.ifra_addr).sin_addr.s_addr = inet_addr("1.2.3.4"); | |
SIN(ifa.ifra_broadaddr).sin_len = sizeof(struct sockaddr_in); | |
SIN(ifa.ifra_broadaddr).sin_family = AF_INET; | |
SIN(ifa.ifra_broadaddr).sin_addr.s_addr = inet_addr("255.255.255.0"); | |
SIN(ifa.ifra_mask).sin_len = sizeof(struct sockaddr_in); | |
SIN(ifa.ifra_mask).sin_family = AF_INET; | |
SIN(ifa.ifra_mask).sin_addr.s_addr = inet_addr("1.2.3.255"); | |
printf("trying to set address to 1.2.3.4/24, go check ifconfig %s and press enter\n", name); | |
if (ioctl(sock, SIOCAIFADDR, &ifa) == -1) | |
err(1, "ioctl(SIOCAIFADDR)"); | |
getchar(); | |
if (ioctl(sock, SIOCGIFFLAGS, &ifr) == -1) | |
err(1, "ioctl(SIOCGIFFLAGS)"); | |
int flags = (ifr.ifr_flags & 0xffff) | (ifr.ifr_flagshigh << 16); | |
flags |= IFF_UP; | |
ifr.ifr_flags = flags & 0xffff; | |
ifr.ifr_flagshigh = flags >> 16; | |
if (ioctl(sock, SIOCSIFFLAGS, &ifr) == -1) | |
err(1, "ioctl(SIOCSIFFLAGS)"); | |
printf("is it up? go check ifconfig %s and press enter\n", name); | |
getchar(); | |
if (ioctl(sock, SIOCIFDESTROY, &ifr) == -1) | |
err(1, "ioctl(SIOCIFDESTROY)"); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment