一种IP的获取方式
一般的来说,获取内网IP比较简单.
1 int main()
2 {
3 char hostname[128];
4 (gethostname(hostname,128)==0)?NULL:MessageBox(NULL,"无法获取网络地址",hostname,MB_OK);
5 struct hostent *pHost = gethostbyname(hostname);
6 char *szLocalIP=new char[sizeof(pHost)];
7 for (int i = 0; pHost != NULL && pHost->h_addr_list[i] != NULL; i++)
8 {
9 strcpy(szLocalIP,(inet_ntoa(*(struct in_addr *)pHost->h_addr_list[i])));
10 }
11 printf("LocalIP : %s \n",szLocalIP);
12 return 0;
13 }
外网IP大多是去通过路由获得,不过我选择了一种相对简单的方式.
1 #include <stdio.h>
2 #include <Wininet.h>
3 #include <string.h>
4 #pragma comment(lib,"Wininet.lib")
5
6 char * GetPosString(char *str,int nBegin,int nEnd)
7 {
8 static char buff[1001] = {0};
9 int j=0;
10 if(nBegin <strlen(str) && nBegin>=0 && strlen(str)<=1000 )
11 {
12 for(int i =nBegin-1;i<=nEnd-1;i++)
13 {
14 buff[j]=str[i];
15 j++;
16 }
17 buff[j]='\0';
18 }
19 return buff;
20 }
21
22 char * GetMarkString(char *str,char szBegin,char szEnd)
23 {
24 char *szOne=strchr(str,szBegin);
25 char *szTwo=strchr(str,szEnd);
26 int nBegin = szOne-str+2;//平时不+2,只是因为那个页面IP前有2个空格....
27 int nEnd = szTwo-str;
28 static char buff[1001] = {0};
29 int j=0;
30 if(nBegin <strlen(str) && nBegin>=0 && strlen(str)<=1000 )
31 {
32 for(int i =nBegin-1;i<=nEnd-1;i++)
33 {
34 buff[j]=str[i];
35 j++;
36 }
37 buff[j]='\0';
38 }
39 return buff;
40 }
41
42 char *GetNetIP()
43 {
44 BOOL bResult = FALSE;
45 HINTERNET hInternet = InternetOpen("CEHTTP", INTERNET_OPEN_TYPE_DIRECT, NULL, NULL, NULL);
46 if(hInternet == NULL)
47 return "InternetOpen Error";
48 HINTERNET hSession= InternetConnect(hInternet, "www.ip138.com", 80, NULL, NULL, INTERNET_SERVICE_HTTP, 0, 0);
49 if(hSession == NULL)
50 return "InternetConnect Error";
51 char* szAccept[] = {"*/*", NULL};
52 HINTERNET hRequest = HttpOpenRequest(hSession, "GET", "/ip2city.asp",
53 NULL, NULL, (LPCSTR*)szAccept, INTERNET_FLAG_NO_CACHE_WRITE, 0);
54 if (hRequest == NULL)
55 return "HttpOpenRequest Error";
56 char headerLanguage[] = "Accept-Language: zh-cn\r\n";
57 char headerEncoding[] = "Accept-Encoding: gzip, deflate\r\n";
58 char headerContentType[] = "Content-Type: text/xml\r\n";
59
60 // 添加header 信息
61 //bResult = HttpAddRequestHeaders(hRequest, headerLanguage, -1, HTTP_ADDREQ_FLAG_ADD|HTTP_ADDREQ_FLAG_REPLACE);
62
63 if(!HttpSendRequest(hRequest,NULL,0,NULL,0))
64 return "HttpSendRequest Error";
65 TCHAR szBuf[256];
66 DWORD_PTR dwRet = -1;
67
68 while (InternetReadFile(hRequest,szBuf,256,&dwRet) && dwRet!= 0)
69 {
70 OutputDebugString(szBuf);
71 }
72 char *szIP;
73 szIP=GetMarkString(((char *)szBuf),'[',']');
74 return szIP;
75 }
76
77
78
79 int main()
80 {
81 printf("NetIP : %s \n",GetNetIP());
82
83 return 0;
84 }
当然,你也许会说如果获取IP的页面失效怎么办.不过我想在自己的服务端多这么个页面应该不是什么问题吧. :)