Lorenzo Colitti | ff6f7fe | 2014-12-08 11:27:41 +0900 | [diff] [blame^] | 1 | /* |
| 2 | * Copyright 2014 The Android Open Source Project |
| 3 | * |
| 4 | * Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | * you may not use this file except in compliance with the License. |
| 6 | * You may obtain a copy of the License at |
| 7 | * |
| 8 | * http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | * |
| 10 | * Unless required by applicable law or agreed to in writing, software |
| 11 | * distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | * See the License for the specific language governing permissions and |
| 14 | * limitations under the License. |
| 15 | * |
| 16 | * tun.c - tun device functions |
| 17 | */ |
| 18 | #include <fcntl.h> |
| 19 | #include <string.h> |
| 20 | #include <unistd.h> |
| 21 | #include <arpa/inet.h> |
| 22 | #include <linux/if.h> |
| 23 | #include <linux/if_tun.h> |
| 24 | #include <sys/ioctl.h> |
| 25 | |
| 26 | /* function: tun_open |
| 27 | * tries to open the tunnel device |
| 28 | */ |
| 29 | int tun_open() { |
| 30 | int fd; |
| 31 | |
| 32 | fd = open("/dev/tun", O_RDWR); |
| 33 | if(fd < 0) { |
| 34 | fd = open("/dev/net/tun", O_RDWR); |
| 35 | } |
| 36 | |
| 37 | return fd; |
| 38 | } |
| 39 | |
| 40 | /* function: tun_alloc |
| 41 | * creates a tun interface and names it |
| 42 | * dev - the name for the new tun device |
| 43 | */ |
| 44 | int tun_alloc(char *dev, int fd) { |
| 45 | struct ifreq ifr; |
| 46 | int err; |
| 47 | |
| 48 | memset(&ifr, 0, sizeof(ifr)); |
| 49 | |
| 50 | ifr.ifr_flags = IFF_TUN; |
| 51 | if( *dev ) { |
| 52 | strncpy(ifr.ifr_name, dev, IFNAMSIZ); |
| 53 | ifr.ifr_name[IFNAMSIZ-1] = '\0'; |
| 54 | } |
| 55 | |
| 56 | if( (err = ioctl(fd, TUNSETIFF, (void *) &ifr)) < 0 ){ |
| 57 | close(fd); |
| 58 | return err; |
| 59 | } |
| 60 | strcpy(dev, ifr.ifr_name); |
| 61 | return 0; |
| 62 | } |