How to get an IP address from network interfaces
Alexander Zhirov
azhirov1991 at gmail.com
Thu Apr 21 07:38:04 UTC 2022
On Thursday, 21 April 2022 at 07:20:30 UTC, dangbinghoo wrote:
> 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;
> }
> }
>
> ```
Gives a lot of errors when compiling
```d
app.d(19): Error: function
`std.stdio.makeGlobal!"core.stdc.stdio.stderr".makeGlobal` at
/usr/include/dlang/dmd/std/stdio.d(5198) conflicts with variable
`core.stdc.stdio.stderr` at
/usr/include/dlang/dmd/core/stdc/stdio.d(927)
app.d(19): Error: function
`core.stdc.stdio.fprintf(shared(_IO_FILE)* stream, scope
const(char*) format, scope const ...)` is not callable using
argument types `(void, string, int)`
app.d(19): cannot pass argument `makeGlobal(StdFileHandle
_iob)()` of type `void` to parameter `shared(_IO_FILE)* stream`
app.d(23): Error: undefined identifier `ifreq`
app.d(26): Error: undefined identifier `string` in package `std`
app.d(39): Error: undefined identifier `macaddr`
app.d(48): Error: undefined identifier `fromStringz`
```
More information about the Digitalmars-d-learn
mailing list