Windows/Linux获取网卡地址方法

#ifndef	LINUX
	#include 
	#pragma comment(lib,"Iphlpapi.lib")
#else
	#define IFRSIZE ((int)(size*sizeof(struct ifreq)))
#endif
/////////////////////////////////////////////////////////////////////////////////////////////////
BYTE __local_netaddress__[8][6]={0};//本机网卡号(包括虚拟网卡)
char __local_ipaddress__[8][16]={0};//本机ip地址


//获取本机网卡地址
DWORD WSYSPLUS_API GetNetcard(BYTE Address[8][6])//不要用NetBios函数,可以被用户屏蔽的
{
	BYTE null_card[6]={0},j=0;
#if(defined WIN32) || (defined WIN64)
	ULONG ulAdapterInfoSize(0);
	GetAdaptersInfo(NULL,&ulAdapterInfoSize);
	if(ulAdapterInfoSize)
	{
		IP_ADAPTER_INFO*pAdapterInfo=(IP_ADAPTER_INFO*)new char[ulAdapterInfoSize];
		IP_ADAPTER_INFO*pAdapterInfoBkp=pAdapterInfo;
		IP_ADDR_STRING* pIPAddr = NULL;
		if(GetAdaptersInfo(pAdapterInfo,&ulAdapterInfoSize)==ERROR_SUCCESS)
		{
			do	//遍历所有适配器
			{
				if(pAdapterInfo->Type==MIB_IF_TYPE_ETHERNET||
					pAdapterInfo->Type==IF_TYPE_IEEE80211)//判断是否为以太网接口
				{
					if(pAdapterInfo->AddressLength==6&&
						memcmp(pAdapterInfo->Address,null_card,6))
					{
						memcpy(Address[j],pAdapterInfo->Address,6);
						pIPAddr = &(pAdapterInfo->IpAddressList);
						strcpy_s(__local_ipaddress__[j], pIPAddr->IpAddress.String);
						if(++j>7) break;
					}
				}
				pAdapterInfo = pAdapterInfo->Next;
			}while(pAdapterInfo);
		}
		delete pAdapterInfoBkp;
	}
#else
    int  sockfd,size=1;
    struct ifconf ifc;
    struct sockaddr_in sa;
    if((sockfd=socket(AF_INET,SOCK_DGRAM,IPPROTO_IP))<0) return(0);
    ifc.ifc_req = NULL;
    do
    {
        ++size;
        if(!(ifc.ifc_req=(ifreq*)realloc(ifc.ifc_req,IFRSIZE))) return(0);
        ifc.ifc_len = IFRSIZE;
        if(ioctl(sockfd,SIOCGIFCONF,&ifc)) return(0);
    }while(IFRSIZE<=ifc.ifc_len);
    struct ifreq *ifr = ifc.ifc_req;
    for(;(char*)ifr<(char*)ifc.ifc_req+ifc.ifc_len;++ifr)
    {
        if(ifr->ifr_addr.sa_data==(ifr+1)->ifr_addr.sa_data) continue;
        if(ioctl(sockfd,SIOCGIFFLAGS,ifr)) continue;
        if(!ioctl(sockfd,SIOCGIFHWADDR,ifr))
        {
            switch(ifr->ifr_hwaddr.sa_family)
            {
            case ARPHRD_NETROM:
            case ARPHRD_ETHER:
            case ARPHRD_PPP:
            case ARPHRD_EETHER:
            case ARPHRD_IEEE802:
                break;
            default:
                continue;
            }
			if(memcmp(&ifr->ifr_addr.sa_data,null_card,6))
			{
				memcpy(Address[j++],&ifr->ifr_addr.sa_data,6);
			}
        }
    }
    close(sockfd);
#endif
	return(j);
}


你可能感兴趣的:(Windows应用层编程)