本文實例講述了vc獲取計算機名和ip地址的方法。分享給大家供大家參考。具體實現方法如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
|
#include <winsock2.h> #include <stdio.h> #pragma comment(lib,"ws2_32.lib") void main() { WSADATA wsadata; WORD dwVersionRequested; int err; err=WSAStartup(dwVersionRequested,&wsadata); char hostname[128]; if (gethostname(hostname,128)==0) { printf ( "%s\n" ,hostname); //計算機名字 } char buf[20]; //memset(buf,0,80); struct hostent *pHost = gethostbyname(hostname); for ( int i = 0; pHost != NULL && pHost->h_addr_list[i] != NULL; i++) { //將它放入字符數組中便于應用 strcpy (buf,inet_ntoa(*( struct in_addr *)pHost->h_addr_list[i])); //inet_ntoa(*(struct in_addr *)pHost->h_addr_list[i]); //IP地址 printf ( "%s\n" ,buf); } WSACleanup(); } |
希望本文所述對大家的VC程序設計有所幫助。