C C 獲取本機名 本機IP 本機MAC

2022-04-11 23:37:23 字數 1575 閱讀 5408

本機名、ip、mac都是一些比較常用網路引數,怎麼用c/c++獲取呢?

研究了兩三個小時...

需要說明的都在**注釋裡

1 #include 2 #include 3 #include 4

5#pragma comment(lib,"ws2_32.lib") //

socket靜態庫,取本機ip用

6#pragma comment(lib,"iphlpapi.lib") //

傳送arp報文要用的靜態庫,取mac用78

/*9取主機名

10成功返回主機名,失敗返回null.

11*/

12char *mygethostname(void

);13

14/*

15取本機ip

16成功返回本機ip,失敗返回null.

17*/

18char *mygethostip(void

);19

20/*

21取本機mac

22成功返回本機mac,失敗返回null.

23*/

24char *mygethostmac(void

);25

26int main(void)27

4546

char *mygethostname(void)47

5758

char *mygethostip(void)59

;62struct hostent *phostinfo =null;

6364 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();

70if

(ip)

7174

else78}

7980

char *mygethostmac(void)81

; //

mac位址長度6位元組

85 ulong umacsize = 6;86

87//

通過arp報文響應獲取mac位址

88 dword dwret = sendarp(ip, 0, &macaddr, &umacsize);

89if (dwret ==no_error)

90102

else

103106

}107

else

108111

return

null;

112 }

效果圖:

獲取本機IP

獲取本機ip char name 255 gethostname name,sizeof name cstring ip lphostent lphost lphost gethostbyname name in addr ppaddr in addr lphost h addr list in a...

獲取本機號碼,本機IP

獲取本機號碼 telephonymanager phonemgr telephonymanager this.getsystemservice context.telephony service txtphonenumber.settext phonemgr.getline1number txtph...

獲取本機IP位址

cstring strlocalip char szhostname 64 memset szhostname,0x00,sizeof szhostname gethostname szhostname,sizeof szhostname phostent phost gethostbyname s...