Tomato 1.24
[tomato.git] / release / src / router / miniupnpd / getifaddr.c
blobfbfa103868d9850b3d9c84ba59edbcd1eeb2aefd
1 /* $Id: getifaddr.c,v 1.9 2008/10/15 10:16:28 nanard Exp $ */
2 /* MiniUPnP project
3 * http://miniupnp.free.fr/ or http://miniupnp.tuxfamily.org/
4 * (c) 2006-2008 Thomas Bernard
5 * This software is subject to the conditions detailed
6 * in the LICENCE file provided within the distribution */
8 #include <string.h>
9 #include <syslog.h>
10 #include <unistd.h>
11 #include <sys/ioctl.h>
12 #include <sys/types.h>
13 #include <sys/socket.h>
14 #include <net/if.h>
15 #include <arpa/inet.h>
16 #include <netinet/in.h>
17 #if defined(sun)
18 #include <sys/sockio.h>
19 #endif
21 #include "getifaddr.h"
23 int
24 getifaddr(const char * ifname, char * buf, int len)
26 /* SIOCGIFADDR struct ifreq * */
27 int s;
28 struct ifreq ifr;
29 int ifrlen;
30 struct sockaddr_in * addr;
31 ifrlen = sizeof(ifr);
32 if(!ifname || ifname[0]=='\0')
33 return -1;
34 s = socket(PF_INET, SOCK_DGRAM, 0);
35 if(s < 0)
37 syslog(LOG_ERR, "socket(PF_INET, SOCK_DGRAM): %m");
38 return -1;
40 strncpy(ifr.ifr_name, ifname, IFNAMSIZ);
41 if(ioctl(s, SIOCGIFADDR, &ifr, &ifrlen) < 0)
43 syslog(LOG_ERR, "ioctl(s, SIOCGIFADDR, ...): %m");
44 close(s);
45 return -1;
47 addr = (struct sockaddr_in *)&ifr.ifr_addr;
48 if(!inet_ntop(AF_INET, &addr->sin_addr, buf, len))
50 syslog(LOG_ERR, "inet_ntop(): %m");
51 close(s);
52 return -1;
54 close(s);
55 return 0;