【原创】C++实现获取本机机器名及外网IP代码
上代码:
1 #include "stdafx.h" 2 #include <WINSOCK2.H> 3 #include <urlmon.h> 4 5 #pragma comment(lib, "ws2_32.lib") 6 #pragma comment(lib, "urlmon.lib") 7 8 #define MAX_SIZE 1024 9 10 11 int GetLocalIP(); 12 int GetInternetIP(); 13 14 int main(int argc, char* argv[]) 15 { 16 GetLocalIP(); 17 GetInternetIP(); 18 return 0; 19 } 20 21 22 int GetLocalIP() 23 { 24 WSADATA wsaData; 25 int err = WSAStartup(MAKEWORD(2, 0), &wsaData); 26 if (err != 0) 27 { 28 return err; 29 } 30 31 char szHostName[MAX_PATH] = {0}; 32 int nRetCode; 33 nRetCode = gethostname(szHostName, sizeof(szHostName)); 34 35 char* lpLocalIP; 36 PHOSTENT hostinfo; 37 38 if (nRetCode != 0) 39 { 40 return WSAGetLastError(); 41 } 42 43 hostinfo = gethostbyname(szHostName); 44 lpLocalIP = inet_ntoa(*(struct in_addr*)*hostinfo->h_addr_list); 45 46 if (szHostName != NULL) 47 { 48 printf("主机名: %s\n", szHostName); 49 printf("本地IP: %s\n", lpLocalIP); 50 } 51 52 WSACleanup(); 53 return 0; 54 } 55 56 int GetInternetIP() 57 { 58 char buf[MAX_PATH] = {0}; //把网页中读出的数据放在此处 59 char chTempIp[128] = {0}; 60 char chIP[64] = {0}; //最终存放IP在此 61 62 //将网页数据写入c:\i.ini文件中 63 URLDownloadToFile(0, "http://iframe.ip138.com/ic.asp", "c:\\i.ini", 0, NULL); 64 65 FILE *fp = fopen("c:\\i.ini", "r"); 66 if (fp != NULL) 67 { 68 // 69 fseek(fp, 0, SEEK_SET); 70 fread(buf, 1, MAX_PATH, fp); 71 fclose(fp); 72 73 //在buf中查找 [ 的位置, iIndex是buf中从[开始剩下的字符串,包括[这个字符串 74 char* iIndex = strstr(buf, "["); 75 if (iIndex) 76 { 77 sprintf(chTempIp, "%s", iIndex); 78 int nBuflen = strlen(chTempIp); 79 80 for (int i = 0; i < nBuflen; i++) 81 { 82 chIP[i] = chTempIp[i+1]; 83 84 //如果发现有 ] 则截断 85 if (chTempIp[i] == ']') 86 { 87 chIP[i-1] = '\0'; 88 //printf("外网IP: %s\n", chIP); 89 } 90 } 91 } 92 93 } 94 95 printf("外网IP: %s\n", chIP); 96 remove("c:\\i.ini"); 97 98 return 0; 99 100 }
Life is like a box of chocolate, you never know what you are going to get.