On Thursday, 21 April 2022 at 07:04:18 UTC, Alexander Zhirov
wrote:
I want to get the IP address of the network interface. There is
both a wireless interface and a wired one. Is it possible,
knowing the name of the network interface, to get its IP
address?
```d
import core.sys.posix.sys.ioctl;
import core.sys.posix.arpa.inet;
import core.stdc.string;
import core.stdc.stdio;
import core.stdc.errno;
import core.sys.posix.stdio;
import core.sys.posix.unistd;
string ip;
int get(string if_name)
{
int s = socket(AF_INET, SOCK_DGRAM, 0);
if (s < 0) {
fprintf(stderr, "Create socket failed!errno=%d", errno);
return -1;
}
ifreq ifr;
uint nIP, nNetmask, nBroadIP;
strcpy(ifr.ifr_name.ptr, std.string.toStringz(if_name));
try {
if (ioctl(s, SIOCGIFHWADDR, &ifr) < 0) {
return -2;
}
}
catch (Exception e) {
writeln("Error operation on netif " ~ if_name);
return -2;
}
memcpy(macaddr.ptr, cast(char *)ifr.ifr_hwaddr.sa_data.ptr, 6);
if (ioctl(s, SIOCGIFADDR, &ifr) < 0) {
nIP = 0;
}
else {
nIP = *cast(uint*)(&ifr.ifr_broadaddr.sa_data[2]);
ip = fromStringz(inet_ntoa(*cast(in_addr*)&nIP)).idup;
}
}
```