首页 > C/C++ > c++ 获取外网IP
2015
04-07

c++ 获取外网IP

1.解析URL使用了 http-parser https://github.com/joyent/http-parser

代码

// dnybz<cnfreebsd@163.com> [4/7/2015]
#include <stdio.h>
#include <WinSock2.h>
#include <Windows.h>
#include "http_parser.h"

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

int get_extranet_ip(__in const char* fetchurl, __out char* ext_ipaddr)
{
	char host[128] = {0};
	char path[260] = {0};
	int port;
	const char *url = fetchurl;
	http_parser_url urlFields;
	const int result = ::http_parser_parse_url(url, strlen(url), 0, &urlFields);
	if (result != 0){ 
		return 1;
	}

	if(urlFields.field_set & (1 << UF_PORT)){
		port = urlFields.port;
	}
	else{
		port = 80;
	}

	if(urlFields.field_set & (1 << UF_HOST) ){
		strncpy(host, url+urlFields.field_data[UF_HOST].off, urlFields.field_data[UF_HOST].len);
		host[urlFields.field_data[UF_HOST].len] = 0;
	}
	if(urlFields.field_set & (1 << UF_PATH)){
		strncpy(path, url+urlFields.field_data[UF_PATH].off, urlFields.field_data[UF_PATH].len);
		path[urlFields.field_data[UF_PATH].len] = 0;
	}

	WSADATA wsaData;
	SOCKET hsock;
	LPHOSTENT lphost;
	SOCKADDR_IN addr;
	if (WSAStartup(MAKEWORD(2,2), &wsaData)== SOCKET_ERROR) { 
		WSACleanup();
		return 1;  
	}

	hsock = socket(PF_INET,SOCK_STREAM,0);
	if (hsock == INVALID_SOCKET)
		return 0;
	lphost = gethostbyname(host);
	addr.sin_family = AF_INET;

	int icount = 0;
	bool is_host = true;
	if(lphost == NULL){	
		do{
			lphost = gethostbyname(host);
			if (lphost != NULL){
				is_host = false;
			}

			if(icount++ > 4){
				return 1;
			}
			Sleep(1000);
		}while (is_host);
	}

	addr.sin_addr.s_addr=1 == SOCKET_ERROR)
		return 0;

	char uriparam[]=   "GET %s HTTP/1.1\n"
		"Accept: image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/x-shockwave-flash, */*\n"
		"Accept-Language: zh-cn\n"
		"User-Agent: Mozilla/4.0\n"
		"Host: %s\n\n\n";
	
	char post_data[4096] = {0};
	sprintf(post_data, uriparam, path, host);

	int  retval= send(hsock, post_data, sizeof(post_data)-1, 0);
	if( SOCKET_ERROR== retval )  return 0;

	char buf[80 * 1024] = {0};
	char tempbuf[4096] = {0};
	while( SOCKET_ERROR != retval && retval>0   ){ 
		memset(tempbuf,0,sizeof(tempbuf));
		retval= recv(hsock ,tempbuf, sizeof(tempbuf),0); 
		strcat(buf, tempbuf);
	}

	if (!strstr(buf, "HTTP/1.1 200 OK")){
		return 1;
	}

	char* pToken = NULL;
	char* pSave = NULL;
	pToken = strtok_s(buf, "[", &pSave);
	if(pToken){
		pToken = strtok_s(NULL, "]", &pSave);
	}

	strncpy(ext_ipaddr, pToken, strlen(pToken));

	return 0;
}

int main()
{
	char extranet_host[128] = {0};
	if (get_extranet_ip("http://1111.ip138.com/ic.asp", extranet_host) == 0)
	{
		printf("Extranet IP: %s", extranet_host);
	}
	return 0;
}

 

  1. LPIN_ADDR)lphost->h_addr)->s_addr; addr.sin_port = ntohs(port); if (connect(hsock,(LPSOCKADDR)&addr, sizeof(addr []
最后编辑:
作者:dnybz
这个作者貌似有点懒,什么都没有留下。