由于工作关系,最近转投VC的开发了。。。当然,还是要从最近本做起的。最近跟网络这块接触较多,写了两段小函数。
获取本机MAC,网上的代码都写烂了,但是异常处理不太好,比如多网卡等情况,于是自己写了一段简单明了靠谱的代码。
具体流程为先获取自己程序所在的网络的网络名,然后根据网络名获取IP,最后sendarp得到MAC。思路清晰。。。。
代码如下:
CString GetLocalIP()
{
CString strResult;
WSADATA wsaData;
char name[255];
PHOSTENT hostinfo;
char *ip = NULL;
if ( WSAStartup( MAKEWORD(2,0), &wsaData ) == 0 )
{
if( gethostname ( name, sizeof(name)) == 0)
{
if((hostinfo = gethostbyname(name)) != NULL)
{
//获得IP
ip = inet_ntoa(*(struct in_addr *)*hostinfo->h_addr_list);
strResult = ip;
}
}
WSACleanup();
}
return strResult;
}
CString GetMac(CString sIP)
{
CString strResult;
unsigned char mac[6]={0};
ULONG ulen=6;
IPAddr destIP=inet_addr(sIP);
if(NO_ERROR==SendARP(destIP,NULL,(PULONG)mac,&ulen))
{
strResult.Format("%02x%02x%02x%02x%02x%02x",mac[0],mac[1],mac[2],mac[3],mac[4],mac[5]);
strResult.MakeUpper(); //转换成大写
}
else
{
strResult = "0000000000";
}
return strResult;
}
使用方法是:
CString sIP;
CString sMac;
sIP= GetLocalIP(); //先获取本机IP
if (sIP.IsEmpty())
{
return; //没有找到IP直接返回
}
sMac = GetMac(sIP);
同样的,获取网关MAC代码类似:
BOOL GetLocalRouteMacAddress()
{
WSADATA wsaData;
char name[255];
PHOSTENT hostinfo;
char *Myip = NULL;
if (WSAStartup( MAKEWORD(2,0), &wsaData ) == 0 ) //初始化
{
//得到当前使用网络中 注册的hostname
if(gethostname ( name, sizeof(name)) == 0)
{
//从hostname得到网络地址 就是正在使用的网络的IP 如果未联网 则此方法无效
if((hostinfo = gethostbyname(name)) != NULL)
{
//获得IP
Myip = inet_ntoa(*(struct in_addr *)*hostinfo->h_addr_list);
}
}
WSACleanup();
}
DWORD dwRetVal = 0;
PIP_ADAPTER_INFO pAdapter = NULL;
PIP_ADAPTER_INFO pAdapterInfo = NULL;
pAdapterInfo = (IP_ADAPTER_INFO *)malloc(sizeof(IP_ADAPTER_INFO));
ULONG ulOutBufLen = sizeof(IP_ADAPTER_INFO);
if(GetAdaptersInfo(pAdapterInfo,&ulOutBufLen) == ERROR_BUFFER_OVERFLOW)
{
free(pAdapterInfo);
pAdapterInfo = (IP_ADAPTER_INFO*)malloc(ulOutBufLen);
}
char szGetWayIp[64] = {0};
unsigned char dwRouteMAC[6] = {6};
if((dwRetVal=GetAdaptersInfo(pAdapterInfo,&ulOutBufLen))==NO_ERROR)
{
pAdapter = pAdapterInfo;
do{
if(pAdapter)
{
printf("%s\r\nTYPE:%d\r\nIP:%s\r\nGATEWAY:%s\r\n",pAdapter->Description,pAdapter->Type,pAdapter->IpAddressList.IpAddress.String,pAdapter->GatewayList.IpAddress.String);
if (strcmp(pAdapter->IpAddressList.IpAddress.String,Myip) == 0)
{
printf("Now In Use!!!!!!!!!!\r\n");
strcpy(szGetWayIp,pAdapter->GatewayList.IpAddress.String);
ULONG uLen=6;
unsigned long dwGetWayIp=inet_addr(szGetWayIp);
if(SendARP(dwGetWayIp,NULL,(PULONG)dwRouteMAC,&uLen)==NO_ERROR)
{
//当前网卡MAC
memcpy(shost,pAdapter->Address,6);
//当前网卡网关MAC
memcpy(dhost,dwRouteMAC,6);
printf("My MAC:%02x:%02x:%02x:%02x:%02x:%02x\r\n",shost[0],shost[1],shost[2],shost[3],shost[4],shost[5]);
printf("GateWay MAC:%02x:%02x:%02x:%02x:%02x:%02x\r\n",dhost[0],dhost[1],dhost[2],dhost[3],dhost[4],dhost[5]);
printf("GateWayIP:%s\r\n",szGetWayIp);
}
}
printf("\r\n\r\n");
pAdapter = pAdapter->Next;
}
}while(pAdapter);
}
free(pAdapterInfo);
return FALSE;
}
大家工作顺利!~~