【原創】C++實現獲取本機機器名及外網IP代碼

上代碼:url

  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 }
相關文章
相關標籤/搜索