libite 2.6.1
ifconfig.c
Go to the documentation of this file.
1/* Fastinit (finit) ifconfig() implementation.
2 *
3 * Copyright (c) 2008-2010 Claudio Matsuoka <http://helllabs.org/finit/>
4 * Copyright (C) 2009-2021 Joachim Wiberg <troglobit@gmail.com>
5 *
6 * Permission is hereby granted, free of charge, to any person obtaining a copy
7 * of this software and associated documentation files (the "Software"), to deal
8 * in the Software without restriction, including without limitation the rights
9 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 * copies of the Software, and to permit persons to whom the Software is
11 * furnished to do so, subject to the following conditions:
12 *
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
15 *
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22 * THE SOFTWARE.
23 */
24
32
33#include <arpa/inet.h>
34#include <errno.h>
35#include <net/if.h>
36#include <netinet/in.h>
37#include <string.h>
38#include <sys/ioctl.h>
39#include <sys/socket.h>
40#include <unistd.h>
41
42extern size_t strlcpy(char *dst, const char *src, size_t siz);
43
53int ifconfig(const char *ifname, const char *addr, const char *mask, int up)
54{
55 int sd, ret = -1;
56 struct ifreq ifr;
57 struct sockaddr_in *sin = (struct sockaddr_in *)&ifr.ifr_addr;
58
59 if ((sd = socket(PF_INET, SOCK_DGRAM, IPPROTO_IP)) < 0)
60 return -1;
61
62 memset(&ifr, 0, sizeof (ifr));
63 strlcpy(ifr.ifr_name, ifname, IFNAMSIZ);
64 ifr.ifr_addr.sa_family = AF_INET;
65
66 if (up) {
67 if (addr) {
68 if (inet_pton(AF_INET, addr, &sin->sin_addr) == 1)
69 ret = ioctl(sd, SIOCSIFADDR, &ifr);
70 }
71
72 /* Non-zero IP address */
73 if (mask && addr && strcmp(addr, "0.0.0.0")) {
74 if (inet_pton(AF_INET, mask, &sin->sin_addr) == -1)
75 ret = ioctl(sd, SIOCSIFNETMASK, &ifr);
76 }
77 }
78
79 if (!ioctl(sd, SIOCGIFFLAGS, &ifr)) {
80 if (up)
81 ifr.ifr_flags |= IFF_UP;
82 else
83 ifr.ifr_flags &= ~IFF_UP;
84
85 ret = ioctl(sd, SIOCSIFFLAGS, &ifr);
86 }
87
88 close(sd);
89
90 return ret;
91}
92
int ifconfig(const char *ifname, const char *addr, const char *mask, int up)
Definition ifconfig.c:53
size_t strlcpy(char *dst, const char *src, size_t siz)
Definition strlcpy.c:44