欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Windows下获取IP地址和MAC地址

程序员文章站 2022-05-17 08:07:34
...

代码说明:

整理电脑发现的代码,有借鉴一些其他人的,但是忘记了出自哪里,如有侵权,请联系我删除。以下代码基于C++进行实现,可以对本机使用的IP地址进行输出打印并打印使用的MAC地址。
运行环境为:VS2013

#include <winsock2.h>
#include <stdio.h>   
#include <stdlib.h>  
#include <string.h>
#include <httpext.h>   
#include <windef.h>   
#include <Nb30.h>
#pragma comment(lib,"ws2_32.lib")
#pragma comment(lib,"netapi32.lib")
void CheckIP(void)
{
	WSADATA wsaData;
	char name[155];
	char *ip;
	PHOSTENT hostinfo;
	if (WSAStartup(MAKEWORD(2, 2), &wsaData) == 0)
	{
		if (gethostname(name, sizeof(name)) == 0)
		{
			if ((hostinfo = gethostbyname(name)) != NULL)
			{
				int i = 0;
				printf("IP COUNT: %d\r\n", hostinfo->h_length);
				for (i = 0; i<hostinfo->h_length; i++)
				{
					ip = inet_ntoa(*(struct in_addr *)hostinfo->h_addr_list[i]);
					printf("IP #%d: %s\n", i + 1, ip);
				}

			}
		}
		WSACleanup();
	}
}
int getMAC(char * mac)
{
	NCB ncb;
	typedef struct _ASTAT_
	{
		ADAPTER_STATUS   adapt;
		NAME_BUFFER   NameBuff[30];
	}ASTAT, *PASTAT;

	ASTAT Adapter;
	typedef struct _LANA_ENUM
	{
		UCHAR length;
		UCHAR lana[MAX_LANA];
	}LANA_ENUM;
	LANA_ENUM lana_enum;
	UCHAR uRetCode;
	memset(&ncb, 0, sizeof(ncb));
	memset(&lana_enum, 0, sizeof(lana_enum));

	ncb.ncb_command = NCBENUM;
	ncb.ncb_buffer = (unsigned char *)&lana_enum;
	ncb.ncb_length = sizeof(LANA_ENUM);
	uRetCode = Netbios(&ncb);
	if (uRetCode != NRC_GOODRET)
		return uRetCode;

	for (int lana = 0; lana < lana_enum.length; lana++)
	{
		ncb.ncb_command = NCBRESET;
		ncb.ncb_lana_num = lana_enum.lana[lana];
		uRetCode = Netbios(&ncb);
		if (uRetCode == NRC_GOODRET)
			break;
	}
	if (uRetCode != NRC_GOODRET)
		return uRetCode;

	memset(&ncb, 0, sizeof(ncb));
	ncb.ncb_command = NCBASTAT;
	ncb.ncb_lana_num = lana_enum.lana[0];
	strcpy_s((char*)ncb.ncb_callname, 5, "*");
	ncb.ncb_buffer = (unsigned char *)&Adapter;
	ncb.ncb_length = sizeof(Adapter);
	uRetCode = Netbios(&ncb);
	if (uRetCode != NRC_GOODRET)
		return uRetCode;
	sprintf_s(mac, 18, "%02X-%02X-%02X-%02X-%02X-%02X",
		Adapter.adapt.adapter_address[0],
		Adapter.adapt.adapter_address[1],
		Adapter.adapt.adapter_address[2],
		Adapter.adapt.adapter_address[3],
		Adapter.adapt.adapter_address[4],
		Adapter.adapt.adapter_address[5]
		);
	return 0;
}
int main(void)
{
	CheckIP();
	char   mac[200];
	getMAC(mac);
	printf(" MAC地址 : %s ", mac);
	getchar();
	return 0;
}

运行结果为:
Windows下获取IP地址和MAC地址本机信息为:
Windows下获取IP地址和MAC地址