博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

得到本地ip

Posted on 2012-01-17 17:36  ccmfc  阅读(231)  评论(0编辑  收藏  举报

#ifndef __JRY_SOCKET_H__
#define __JRY_SOCKET_H__
typedef enum {
SUCCESS,
FAIL,
I_OPEN_FAIL,
I_OPENURL_FAIL,
I_READFILE_FAIL,
H_QUERYINFO_FAIL,
}ERRORFLAGS;

int JRY_WSASTARUP();
int jry_open_url(char * url, char ** buf, size_t * size);
char* jry_get_localip(char *);

#endif

 

#include<windows.h>
#include<Wininet.h>
#pragma comment(lib,"WinInet.lib")
#pragma comment(lib,"ws2_32")

#define JRY_WSACLEANUP() WSACleanup()

int JRY_WSASTARUP()
{
WSAData wsaData={0};
WORD wVersionRequested=0;
wVersionRequested = MAKEWORD( 2, 0);
if(WSAStartup(wVersionRequested, &wsaData))return 0;
return 1;
}

int jry_open_url(char * url, char ** buf, size_t * size)
{
HINTERNET hSession=0;
HINTERNET hRequest=0;
ERRORFLAGS iret=SUCCESS;
char qbuf[32]={0};
unsigned long qsize=sizeof(qbuf);

do
{
char *lpszAgent="InetURL/1.0";
int dwAccessType=INTERNET_OPEN_TYPE_DIRECT;

if(!url || !size){iret=FAIL;break;}

hSession = ::InternetOpen(lpszAgent, dwAccessType, NULL, NULL, 0);
if(!hSession){iret=I_OPEN_FAIL;break;}

hRequest=::InternetOpenUrl(hSession, url, NULL, 0, 0, 0);
if(!hRequest){iret=I_OPENURL_FAIL;break;}

//if(!::HttpQueryInfo(hRequest, HTTP_QUERY_ALLOW , qbuf, &qsize,0))break;
if(!::HttpQueryInfo(hRequest, HTTP_QUERY_CONTENT_LENGTH, qbuf, &qsize,0)){iret=H_QUERYINFO_FAIL;break;}

*size=atol(qbuf);
*buf=(char*)malloc(atol(qbuf));
if(!*buf){iret=FAIL;break;}

if(!InternetReadFile(hRequest, *buf, *size, (unsigned long *)size)){iret=I_READFILE_FAIL;break;}

} while (0);

if(hRequest)InternetCloseHandle(hRequest);
if(hSession)InternetCloseHandle(hSession);
return iret;
}

char* jry_get_localip(char *ip)
{
char name[255]={0};
hostent *phost=NULL;
do
{
if(!JRY_WSASTARUP())break;
if(gethostname(name,sizeof(name)))break;
phost=gethostbyname(name);
if(!phost)break;
ip=inet_ntoa(*(struct in_addr*)*phost->h_addr_list);
} while (0);
JRY_WSACLEANUP();
return ip;
}