C语言实现Windows下获取IP和MAC地址。

C语言实现Windows下获取IP和MAC地址。

 1 #include <winsock2.h>
 2 #include <stdio.h>   
 3 #include <stdlib.h>  
 4 #include <string.h>
 5 #include <httpext.h>   
 6 #include <windef.h>   
 7 #include <Nb30.h>
 8 #pragma comment(lib,"ws2_32.lib")
 9 #pragma comment(lib,"netapi32.lib")
10 void CheckIP(void)
11 {
12     WSADATA wsaData;
13     char name[155];
14     char *ip;
15     PHOSTENT hostinfo;
16     if (WSAStartup(MAKEWORD(2, 0), &wsaData) == 0)
17     {
18         if (gethostname(name, sizeof(name)) == 0)
19         {
20             if ((hostinfo = gethostbyname(name)) != NULL)
21             {
22                 ip = inet_ntoa(*(struct in_addr *)*hostinfo->h_addr_list);
23                 printf(" IP地址: %s ", ip);
24             }
25         }
26         WSACleanup();
27     }
28 }
29 int getMAC(char * mac)
30 {
31     NCB ncb;
32     typedef struct _ASTAT_
33     {
34         ADAPTER_STATUS   adapt;
35         NAME_BUFFER   NameBuff[30];
36     }ASTAT, *PASTAT;
37 
38     ASTAT Adapter;
39     typedef struct _LANA_ENUM
40     {
41         UCHAR length;
42         UCHAR lana[MAX_LANA];
43     }LANA_ENUM;
44     LANA_ENUM lana_enum;
45     UCHAR uRetCode;
46     memset(&ncb, 0, sizeof(ncb));
47     memset(&lana_enum, 0, sizeof(lana_enum));
48 
49     ncb.ncb_command = NCBENUM;
50     ncb.ncb_buffer = (unsigned char *)&lana_enum;
51     ncb.ncb_length = sizeof(LANA_ENUM);
52     uRetCode = Netbios(&ncb);
53     if (uRetCode != NRC_GOODRET)
54         return uRetCode;
55 
56     for (int lana = 0; lana<lana_enum.length; lana++)
57     {
58         ncb.ncb_command = NCBRESET;
59         ncb.ncb_lana_num = lana_enum.lana[lana];
60         uRetCode = Netbios(&ncb);
61         if (uRetCode == NRC_GOODRET)
62             break;
63     }
64     if (uRetCode != NRC_GOODRET)
65         return uRetCode;
66 
67     memset(&ncb, 0, sizeof(ncb));
68     ncb.ncb_command = NCBASTAT;
69     ncb.ncb_lana_num = lana_enum.lana[0];
70     strcpy_s((char*)ncb.ncb_callname,5, "*");
71     ncb.ncb_buffer = (unsigned char *)&Adapter;
72     ncb.ncb_length = sizeof(Adapter);
73     uRetCode = Netbios(&ncb);
74     if (uRetCode != NRC_GOODRET)
75         return uRetCode;
76     sprintf_s(mac,18, "%02X-%02X-%02X-%02X-%02X-%02X",
77         Adapter.adapt.adapter_address[0],
78         Adapter.adapt.adapter_address[1],
79         Adapter.adapt.adapter_address[2],
80         Adapter.adapt.adapter_address[3],
81         Adapter.adapt.adapter_address[4],
82         Adapter.adapt.adapter_address[5]
83         );
84     return 0;
85 }
86 int main(void)
87 {
88     CheckIP();
89     char   mac[200];
90     getMAC(mac);
91     printf(" mac地址 : %s ", mac);
92     getchar();
93     return 0;
94 }

posted @ 2014-04-09 20:42  随风.Geek  阅读(7384)  评论(0编辑  收藏  举报