c++获取本机MAC地址、IP地址、默认网关、子网掩码

#include 
#include "Iphlpapi.h"
#include 
using namespace std;

#pragma comment(lib,"ws2_32")
#pragma comment(lib,"Iphlpapi")

bool GetGlobalData(u_char* ucLocalMac, DWORD& dwGatewayIp, DWORD& dwLocalIp, DWORD& dwMask)
{
    PIP_ADAPTER_INFO pAdapterInfo = NULL;
    ULONG uLen = 0;

    //为适配器申请内存
    ::GetAdaptersInfo(pAdapterInfo,&uLen);
    pAdapterInfo = (PIP_ADAPTER_INFO)::GlobalAlloc(GPTR, uLen);

    //取得适配器的结构信息
    if (::GetAdaptersInfo(pAdapterInfo, &uLen) == ERROR_SUCCESS)
    {
        if (pAdapterInfo != NULL)
        {
            memcpy(ucLocalMac, pAdapterInfo->Address, 6);
            dwGatewayIp = ::inet_addr(pAdapterInfo->GatewayList.IpAddress.String);
            dwLocalIp = ::inet_addr(pAdapterInfo->IpAddressList.IpAddress.String);
            dwMask = ::inet_addr(pAdapterInfo->IpAddressList.IpMask.String);

            return true;
        }
    }

    return false;
}

int main()
{
    u_char ucLocalMac[6];   //本机MAC地址
    DWORD dwGatewayIp=0 ;       //网关Ip
    DWORD dwLocalIp=0 ;     //本机Ip
    DWORD dwMask=0 ;            //子网掩码

    //获取本机MAC、IP、网关Ip、子网掩码
    GetGlobalData( ucLocalMac,  dwGatewayIp,  dwLocalIp,  dwMask);

    //打印MAC
    printf("MAC Address:%02X-%02X-%02X-%02X-%02X-%02X\n", ucLocalMac[0], ucLocalMac[1], ucLocalMac[2], ucLocalMac[3], ucLocalMac[4], ucLocalMac[5]);
    
    //打印默认网关
    in_addr addr;
    addr.S_un.S_addr = dwGatewayIp;
    printf("Gateway:%s\n", ::inet_ntoa(addr));

    //打印本机IP
    addr.S_un.S_addr = dwLocalIp;
    printf("IP Address:%s\n", ::inet_ntoa(addr));

    //打印MASK地址
    addr.S_un.S_addr = dwMask;
    printf("Mask:%s\n", ::inet_ntoa(addr));


    return 0;
}

你可能感兴趣的:(c++获取本机MAC地址、IP地址、默认网关、子网掩码)