获取本地IP地址信息

版权声明:本文为YuanChuang文章,未经博主允许转载。 https://blog.csdn.net/zzy1448331580/article/details/86764287
/*
获取本地IP信息
*/
#include <windows.h>
#include <stdio.h>
#include <assert.h>
#include <IPHlpApi.h>
#pragma comment(lib,"iphlpapi")
#pragma comment(lib,"ws2_32")

int main(_In_ int _Argc, _In_reads_(_Argc) _Pre_z_ char ** _Argv, _In_z_ char ** _Env)
{
	PIP_ADAPTER_INFO pIpInfo = { 0 };
	ULONG ulIpSize = 0;

	//获取需要的内存
	::GetAdaptersInfo(pIpInfo, &ulIpSize);
	assert(ulIpSize!=0);

	pIpInfo = (PIP_ADAPTER_INFO)::malloc(ulIpSize);
	assert(pIpInfo);

	assert(::GetAdaptersInfo(pIpInfo, &ulIpSize) == ERROR_SUCCESS);
	UCHAR szMac[6] = { 0 };
	DWORD dwGateWay = 0;
	DWORD dwLocalIP = 0;
	DWORD dwMask = 0;

	::memcpy(szMac,pIpInfo->Address,6);
	dwGateWay = ::inet_addr(pIpInfo->GatewayList.IpAddress.String);
	dwLocalIP = ::inet_addr(pIpInfo->IpAddressList.IpAddress.String);
	dwMask = ::inet_addr(pIpInfo->IpAddressList.IpMask.String);

	in_addr addr = { 0 };
	addr.S_un.S_addr = dwGateWay;
	printf("网关IP %s \n",::inet_ntoa(addr));

	addr.S_un.S_addr = dwLocalIP = dwLocalIP;
	printf("本地IP %s \n",::inet_ntoa(addr));

	addr.S_un.S_addr = dwMask;
	printf("地址掩码 %s \n",::inet_ntoa(addr));

	printf("MAC地址 %02X-%02X-%02X-%02X-%02X-%02X \n",
		szMac[0], szMac[1], szMac[2], szMac[3], szMac[4], szMac[5]);

	system("pause");
	return 0;
}

猜你喜欢

转载自blog.csdn.net/zzy1448331580/article/details/86764287
今日推荐