How can i find my LAN IP Address using std.socket?

cc cc at nevernet.com
Sun Feb 18 10:21:37 UTC 2024


On Tuesday, 4 February 2014 at 13:02:26 UTC, TheFlyingFiddle 
wrote:
> I'm trying to find my own ip address using std.socket with 
> little success. How would i go about doing this? (It should be 
> a AddressFamily.INET socket)

On Windows, you can use the Win32`GetAdaptersInfo`[1] function to 
get a list of IPv4 adapters and addresses.  If you need IPv6 
addresses or other more modern features, there is the 
`GetAdaptersAddresses`[2] function, however it doesn't seem the 
necessary Windows headers (IPTypes.h / ifdef.h) have been ported 
to D for this yet.

[1] 
https://learn.microsoft.com/en-us/windows/win32/api/iphlpapi/nf-iphlpapi-getadaptersinfo
[2] 
https://learn.microsoft.com/en-us/windows/win32/api/iphlpapi/nf-iphlpapi-getadaptersaddresses

As I attempt to post this, I now see this thread is... 10 years 
old.  Oh well, still relevant I think.

```d
import std.string;
pragma(lib, `mingw/iphlpapi.lib`); // included with dmd

struct Adapter {
	string name;
	string desc;
	struct IPMask {
		string ip;
		string mask;
	}
	IPMask[] addresses;
}

Adapter[] getAdapters() {
	import core.sys.windows.windows;
	//import core.sys.windows.nspapi;
	import core.sys.windows.iptypes;
	import core.sys.windows.iphlpapi;

	void[] buf;
	uint size = 0;
	auto ret = GetAdaptersInfo(null, &size);
	assert(ret == ERROR_BUFFER_OVERFLOW && size > 0, "Expected 
GetAdaptersInfo to return ERROR_BUFFER_OVERFLOW to query size of 
buffer");
	buf.length = size;
	ret = GetAdaptersInfo(cast(IP_ADAPTER_INFO*) buf.ptr, &size);
	assert(!ret, "GetAdaptersInfo error");

	auto adpt = cast(IP_ADAPTER_INFO*) buf.ptr;

	Adapter[] adapters;

	while (adpt) {
		scope(success) adpt = adpt.Next;

		Adapter adapter;
		adapter.name = adpt.AdapterName.fromStringz.idup;
		adapter.desc = adpt.Description.fromStringz.idup;

		IP_ADDR_STRING addr = adpt.IpAddressList;
		auto paddr = &addr;
		while (paddr) {
			scope(success) paddr = addr.Next;
			adapter.addresses ~= 
Adapter.IPMask(paddr.IpAddress.String.fromStringz.idup, 
paddr.IpMask.String.fromStringz.idup);
		}
		adapters ~= adapter;
	}
	return adapters;
}

void main() {
	import std.stdio;
	auto adapters = getAdapters();
	adapters.writeln;
}
```


More information about the Digitalmars-d-learn mailing list