获得MAC地址即子网掩码等

本文介绍了一个C++程序,用于获取并显示本地计算机的网络配置信息,包括IP地址、子网掩码、默认网关和MAC地址等。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include <windows.h>
#include <stdio.h>
#include <Iphlpapi.h>
#include <iostream>

using namespace std;

#pragma comment(lib, "Iphlpapi.lib")
#pragma comment(lib, "WS2_32.lib")

u_char g_ucLocalMac[6];
DWORD g_dwGatewayIP;
DWORD g_dwLocalIP;
DWORD g_dwMask;

BOOL GetGloballData()
{
 PIP_ADAPTER_INFO pAdapterInfo = NULL;
 ULONG ulLen = 0;

 ::GetAdaptersInfo(pAdapterInfo, &ulLen);

 pAdapterInfo = (PIP_ADAPTER_INFO)::GlobalAlloc(GPTR, ulLen);

 if (::GetAdaptersInfo(pAdapterInfo, &ulLen) == ERROR_SUCCESS)
 {
  if (pAdapterInfo != NULL)
  {
   memcpy(g_ucLocalMac, pAdapterInfo->Address, 6);
   g_dwGatewayIP = ::inet_addr(pAdapterInfo->GatewayList.IpAddress.String);
   g_dwLocalIP = ::inet_addr(pAdapterInfo->IpAddressList.IpAddress.String);
   g_dwMask = ::inet_addr(pAdapterInfo->IpAddressList.IpMask.String);
  }
 }

 cout << "-------- local workstation information ------------" << endl;

 in_addr in;
 in.S_un.S_addr = g_dwLocalIP;
 
 cout << "IP address: " << ::inet_ntoa(in) << endl;

 in.S_un.S_addr = g_dwMask;
 cout << "subnet mask: " << ::inet_ntoa(in) << endl;

 in.S_un.S_addr = g_dwGatewayIP;
 cout << "default gataway: " << ::inet_ntoa(in) << endl;

 u_char* p = g_ucLocalMac;

 char str[100] = "/0";

 sprintf(str, "%02x-%02x-%02x-%02x-%02x-%02x", p[0], p[1], p[2], p[3], p[4], p[5]);

 cout << "mac address: " << str << endl;

 return TRUE;
}

int main()
{
 WSADATA wsaData;
 WORD sockVersion = MAKEWORD(2, 2);

 if (WSAStartup(sockVersion, &wsaData) != 0)
 {
  cout << "initlization failed!" << endl;
  exit(0);
 }

 GetGloballData();

 WSACleanup();
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值