C/C++获取本机名+本机IP+本机MAC

本机名、IP、MAC都是一些比较常用网络参数,怎么用C/C++获取呢?

研究了两三个小时...

需要说明的都在代码注释里

  1 #include <stdio.h>
  2 #include <Windows.h>
  3 #include <IPHlpApi.h>
  4 
  5 #pragma comment(lib,"ws2_32.lib")    // Socket静态库,取本机IP用
  6 #pragma comment(lib,"IPHlpApi.lib")    // 发送ARP报文要用的静态库,取MAC用
  7 
  8 /*
  9     取主机名
 10     成功返回主机名,失败返回NULL.
 11 */
 12 char *MyGetHostName(void);
 13 
 14 /*
 15     取本机IP
 16     成功返回本机IP,失败返回NULL.
 17 */
 18 char *MyGetHostIp(void);
 19 
 20 /*
 21     取本机MAC
 22     成功返回本机MAC,失败返回NULL.
 23 */
 24 char *MyGetHostMac(void);
 25 
 26 int main(void)
 27 {
 28     char *lpName = NULL;
 29     char *lpIp = NULL;
 30     char *lpMac = NULL;
 31 
 32     lpName = MyGetHostName();
 33     lpIp = MyGetHostIp();
 34     lpMac = MyGetHostMac();
 35     printf("PCName : %s\n", lpName);
 36     printf("IPAddr : %s\n", lpIp);
 37     printf("M A C  : %s\n", lpMac);
 38     
 39     free(lpName);
 40     free(lpIp);
 41     free(lpMac);
 42     system("pause");
 43     return 0;
 44 }
 45 
 46 char *MyGetHostName(void)
 47 {
 48     char *lpName = NULL;
 49     DWORD dwLen = 0;
 50 
 51     GetComputerName(NULL, &dwLen);
 52     lpName = (char *)malloc(dwLen);
 53     memset(lpName, 0, dwLen);
 54     GetComputerName(lpName, &dwLen);
 55     return (lpName ? lpName : NULL);
 56 }
 57 
 58 char *MyGetHostIp(void)
 59 {
 60     char *ip = NULL;
 61     WSADATA wsaData = { 0 };
 62     struct hostent *phostinfo = NULL;
 63     
 64     ip = (char *)malloc(sizeof(char)* 16);
 65     memset(ip, 0, 16);
 66     WSAStartup(MAKEWORD(2, 2), &wsaData);
 67     phostinfo = gethostbyname("");
 68     lstrcpyn(ip, inet_ntoa(*(struct in_addr *)(*phostinfo->h_addr_list)), 16);
 69     WSACleanup();
 70     if (ip)
 71     {
 72         return ip;
 73     }
 74     else {
 75         free(ip);
 76         return NULL;
 77     }
 78 }
 79 
 80 char *MyGetHostMac(void)
 81 {
 82     IPAddr ip = inet_addr(MyGetHostIp());
 83     PVOID *pMac = NULL;
 84     ULONG MacAddr[2] = { 0 };    // Mac地址长度6字节
 85     ULONG uMacSize = 6;
 86     
 87     // 通过ARP报文响应获取MAC地址
 88     DWORD dwRet = SendARP(ip, 0, &MacAddr, &uMacSize);
 89     if (dwRet == NO_ERROR)
 90     {
 91         BYTE *bPhyAddr = (BYTE *)MacAddr;
 92         
 93         if (uMacSize)
 94         {
 95             char *sMac = (char *)malloc(sizeof(char)* 18);
 96             int n = 0;
 97 
 98             memset(sMac, 0, 18);
 99             sprintf_s(sMac, (size_t)18, "%.2X-%.2X-%.2X-%.2X-%.2X-%.2X", (int)bPhyAddr[0], (int)bPhyAddr[1], (int)bPhyAddr[2], (int)bPhyAddr[3], (int)bPhyAddr[4], (int)bPhyAddr[5]);
100             return sMac;
101         }
102         else
103         {
104             printf("Mac地址获取失败!\n");
105         }
106     }
107     else
108     {
109         printf("ARP报文发送失败:%d\n",dwRet);
110     }
111     return NULL;
112 }

 

效果图:

posted @ 2018-07-18 05:25  BiaoGe  阅读(5046)  评论(1编辑  收藏  举报