GetInterfaceInfo function of win32 api
Mike Parker
aldacron at gmail.com
Thu Jun 8 07:56:16 UTC 2023
On Thursday, 8 June 2023 at 07:01:44 UTC, Benny wrote:
> I got something! thank you.
> now I need to understand how can I get the properties of the
> GetInterfaceInfo
>
> ```
> import core.sys.windows.iphlpapi;
> import std.stdio;
> import core.stdc.stdlib;
>
> void main()
> {
> uint* i;
> i = cast(uint*) malloc(10);
> auto h = GetInterfaceInfo(null, i);
> writefln("%s", h);
> writeln("Hello, World!");
> }
>
> ```
>
> this got me 122
Alright. I've never used this function, so I referenced the
documentation here:
https://learn.microsoft.com/en-us/windows/win32/api/iphlpapi/nf-iphlpapi-getinterfaceinfo
First, you don't need to allocate i with malloc. Just declare it
as a uint and give the function a pointer to it.
Second, the function is intended to be called twice. The first
time with null for the first parameter as you've done here. After
that call, the value in i should be the size of the memory you
need to allocate for the first parameter on the second call. In
the second call, the data you want will be stored in that pointer.
Third, the first parameter is of type PIP_INTERACE_INFO, which in
Windows lingo means "pointer to IP_INTERFACE_INFO". That's
declared in the ipexport module.
Here's a working example. I chose to use the GC rather than
malloc.
```d
import core.sys.windows.windows, // For the error codes
core.sys.windows.iphlpapi,
core.sys.windows.ipexport;
import std.stdio,
std.string;
void main()
{
IP_INTERFACE_INFO* pinfo;
uint buflen;
// Get the size needed to alloc pinfo
uint ret = GetInterfaceInfo(null, &buflen);
if(ret == ERROR_INSUFFICIENT_BUFFER) {
// Allocate pinfo, but let's not use malloc
ubyte[] buf = new ubyte[](buflen);
pinfo = cast(IP_INTERFACE_INFO*)buf.ptr;
}
// Call the function a second time to get the data
ret = GetInterfaceInfo(pinfo, &buflen);
if(ret == NO_ERROR) {
writeln("Number of adapters: ", pinfo.NumAdapters);
for(size_t i = 0; i<pinfo.NumAdapters; ++i) {
writefln("Adapter Index[%s]: %s", i,
pinfo.Adapter[i].Index);
writefln("Adapter Index[%s]: %s", i,
fromStringz(pinfo.Adapter[i].Name));
}
}
else if(ret == ERROR_NO_DATA) {
writeln("No network adapters found");
}
else {
writeln("GetInterfaceInfo failure: ", ret);
}
}
```
More information about the Digitalmars-d-learn
mailing list