获取本机IP和MAC地址

Posted qianbo_insist

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了获取本机IP和MAC地址相关的知识,希望对你有一定的参考价值。

1、定义数据结构

typedef struct s_ip_fname
{
	//一个网卡可能有多个IP地址
	std::vector<std::string> ips;
	std::string mac;
}s_ip_fname;

2、 函数

static int get_ipfname(std::vector<s_ip_fname> &ff)
{
#define ADDR(x) pIpAdapterInfo->Address[x]
	PIP_ADAPTER_INFO pIpAdapterInfo = new IP_ADAPTER_INFO();
	unsigned long stSize = sizeof(IP_ADAPTER_INFO);
	int nRel = GetAdaptersInfo(pIpAdapterInfo, &stSize);
	DWORD netCardNum = 0;
	GetNumberOfInterfaces(&netCardNum);
	int IPnumPerNetCard = 0;
	if (ERROR_BUFFER_OVERFLOW == nRel)
	{
		delete pIpAdapterInfo;
		pIpAdapterInfo = (PIP_ADAPTER_INFO)new BYTE[stSize];
		nRel = GetAdaptersInfo(pIpAdapterInfo, &stSize);
		//return -1;
	}
	if (ERROR_SUCCESS == nRel)
	{
		//maybe we have >1 network card
		while (pIpAdapterInfo)
		{
			s_ip_fname ipf;
			switch (pIpAdapterInfo->Type)
			{
			case MIB_IF_TYPE_OTHER:
				//cout << "OTHER" << endl; 
				break;
			case MIB_IF_TYPE_ETHERNET:
				//cout << "ETHERNET" << endl; 
				break;
			case MIB_IF_TYPE_TOKENRING:
				//cout << "TOKENRING" << endl; 
				break;
			case MIB_IF_TYPE_FDDI:
				//cout << "FDDI" << endl; 
				break;
			case MIB_IF_TYPE_PPP:
				//cout << "PPP" << endl; 
				break;
			case MIB_IF_TYPE_LOOPBACK:
				//cout << "LOOPBACK" << endl; 
				break;
			case MIB_IF_TYPE_SLIP:
				//cout << "SLIP" << endl; 
				break;
			default:
				//cout << "" << endl; 
				break;
			}
			char buffer[128];
			sprintf(buffer, "%02X-%02X-%02X-%02X-%02X-%02X",
				//sprintf(buffer, "%02X-%02X-%02X-%02X-%02X-%02X-%02X-%02X",
				ADDR(0), ADDR(1), ADDR(2), ADDR(3), ADDR(4), ADDR(5));
			ipf.mac = buffer;
			IPnumPerNetCard = 0;
			//可能网卡有多IP
			IP_ADDR_STRING *pIpAddrString = &(pIpAdapterInfo->IpAddressList);
			do
			{
				ipf.ips.push_back(pIpAddrString->IpAddress.String);
				pIpAddrString = pIpAddrString->Next;

			} while (pIpAddrString);
			ff.push_back(ipf);
			pIpAdapterInfo = pIpAdapterInfo->Next;
		}
	}
	//释放内存空间
	if (pIpAdapterInfo)
	{
		delete pIpAdapterInfo;
	}
	return 0;
}

3、函数调用封装

只获取第一个IP地址
std::string main_ip()
{
std::vector<s_ip_fname> ip_mac_vector;
get_ipfname(ip_mac_vector);
std::string ip;
if (ip_mac_vector.size() == 0)
return ip;
auto it = ip_mac_vector.begin();
if(it->ips.size()>0)
ip = it->ips[0];
return ip;
}

以上是关于获取本机IP和MAC地址的主要内容,如果未能解决你的问题,请参考以下文章

java获取本机IP地址和MAC地址的方法

获取本机IP和MAC地址

QT获取本机IP和Mac地址

获取客户端的ip地址与mac地址总结

Java获取本机的IP与MAC地址

如何在Node.js中获取本机本地IP地址