From 797e132d0c809f86da9c2b374cadbfa29edccc42 Mon Sep 17 00:00:00 2001 From: Andreas Kling Date: Mon, 23 Sep 2019 19:06:53 +0200 Subject: [PATCH] ifconfig: Allow setting an adapter's IPv4 address You can now do things like "ifconfig e1k0 192.168.1.2" to set the IPv4 address of e1k0. Pretty neat! --- Userland/ifconfig.cpp | 36 +++++++++++++++++++++++++++++++++--- 1 file changed, 33 insertions(+), 3 deletions(-) diff --git a/Userland/ifconfig.cpp b/Userland/ifconfig.cpp index 4b6f303e54..48f32e184e 100644 --- a/Userland/ifconfig.cpp +++ b/Userland/ifconfig.cpp @@ -1,9 +1,12 @@ -#include #include #include +#include #include #include +#include #include +#include +#include String si_bytes(unsigned bytes) { @@ -18,8 +21,35 @@ String si_bytes(unsigned bytes) int main(int argc, char** argv) { - UNUSED_PARAM(argc); - UNUSED_PARAM(argv); + if (argc == 3) { + String ifname = argv[1]; + auto address = IPv4Address::from_string(argv[2]); + + if (!address.has_value()) { + fprintf(stderr, "Invalid IPv4 address: '%s'\n", argv[2]); + return 1; + } + + int fd = socket(AF_INET, SOCK_DGRAM, IPPROTO_IP); + if (fd < 0) { + perror("socket"); + return 1; + } + + struct ifreq ifr; + memset(&ifr, 0, sizeof(ifr)); + + strncpy(ifr.ifr_name, ifname.characters(), IFNAMSIZ); + ifr.ifr_addr.sa_family = AF_INET; + ((sockaddr_in&)ifr.ifr_addr).sin_addr.s_addr = address.value().to_in_addr_t(); + + int rc = ioctl(fd, SIOCSIFADDR, &ifr); + if (rc < 0) { + perror("ioctl(SIOCSIFADDR)"); + return 1; + } + return 0; + } auto file = CFile::construct("/proc/net/adapters"); if (!file->open(CIODevice::ReadOnly)) {