Add network interface helper functions
[connman] / plugins / net.c
1 /*
2  *
3  *  Connection Manager
4  *
5  *  Copyright (C) 2007  Intel Corporation. All rights reserved.
6  *
7  *  This program is free software; you can redistribute it and/or modify
8  *  it under the terms of the GNU General Public License version 2 as
9  *  published by the Free Software Foundation.
10  *
11  *  This program is distributed in the hope that it will be useful,
12  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
13  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  *  GNU General Public License for more details.
15  *
16  *  You should have received a copy of the GNU General Public License
17  *  along with this program; if not, write to the Free Software
18  *  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
19  *
20  */
21
22 #ifdef HAVE_CONFIG_H
23 #include <config.h>
24 #endif
25
26 #include <stdio.h>
27 #include <errno.h>
28 #include <fcntl.h>
29 #include <unistd.h>
30 #include <stdlib.h>
31 #include <string.h>
32 #include <sys/ioctl.h>
33 #include <net/if.h>
34
35 #include "net.h"
36
37 static int __net_ifindex(const char *sysfs)
38 {
39         char *pathname;
40         char buf[8];
41         size_t size;
42         ssize_t len;
43         int fd, val = -EIO;
44
45         if (sysfs == NULL)
46                 return -1;
47
48         size = strlen(sysfs) + 9;
49
50         pathname = malloc(size);
51
52         sprintf(pathname, "%s/ifindex", sysfs);
53
54         fd = open(pathname, O_RDONLY);
55
56         free(pathname);
57
58         if (fd < 0)
59                 return -errno;
60
61         memset(buf, 0, sizeof(buf));
62
63         len = read(fd, buf, sizeof(buf) - 1);
64         if (len < 0) {
65                 val = -errno;
66                 goto done;
67         }
68
69         val = atoi(buf);
70
71 done:
72         close(fd);
73
74         return val;
75 }
76
77 char *__net_ifname(const char *sysfs)
78 {
79         struct ifreq ifr;
80         int sk, err, ifindex;
81
82         ifindex = __net_ifindex(sysfs);
83         if (ifindex < 0)
84                 return NULL;
85
86         sk = socket (PF_INET, SOCK_DGRAM, 0);
87         if (sk < 0)
88                 return NULL;
89
90         memset(&ifr, 0, sizeof(ifr));
91         ifr.ifr_ifindex = ifindex;
92
93         err = ioctl(sk, SIOCGIFNAME, &ifr);
94
95         close(sk);
96
97         if (err < 0)
98                 return NULL;
99
100         return strdup(ifr.ifr_name);
101 }
102
103 void __net_free(void *ptr)
104 {
105         if (ptr)
106                 free(ptr);
107 }