Are you sure your szGET buffer is enough for the string you are trying to put into it?
Code:
#include <string.h>
#include <ctype.h>
#include <windows.h>
#include <winsock.h>
char *GetIP(char *pszDest, char *pszDesc, char *pszBuf, int iLen, unsigned short usPort)
{
SOCKET sock;
WSADATA wsaD;
SOCKADDR_IN sin;
PHOSTENT pHostEnt;
char *szGET, szBuf[1024], *p, *ip;
int i, j;
size_t getBufSize = 0;
WSAStartup(0x101, &wsaD);
sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if(!(pHostEnt = gethostbyname(pszDest)))
goto Failure;
sin.sin_family = AF_INET;
sin.sin_addr = *((PIN_ADDR)pHostEnt->h_addr);
sin.sin_port = htons(usPort);
if(connect(sock, (PSOCKADDR)&sin, sizeof(SOCKADDR_IN)) == SOCKET_ERROR){
goto Failure;
}/*if*/
/*Grab the right sized buffer needed*/
getBufSize = strlen("GET / HTTP/1.1\r\nHost: %s\r\nConnection: close\r\n\r\n") + strlen(pszDest) + 2;
/*Allocate The Memory For The Buffer, NOTE: This seems to be where you corruption was, was the buffer big enough?*/
szGET = malloc(getBufSize * sizeof(szGET));
/*Make sure we allocated properly*/
if(NULL == szGET){
goto Failure;
}/*if*/
/*Zero out the buffer*/
memset(szGET, '\0', getBufSize);
/*Format The Message To Send To The Host*/
wsprintf(szGET, "GET / HTTP/1.1\r\nHost: %s\r\nConnection: close\r\n\r\n", pszDest);
/*Send the message to the host*/
if(send(sock, szGET, strlen(szGET) + 1, 0) == SOCKET_ERROR){
goto Failure;
}/*if*/
do {
i = recv(sock, szBuf, 1023, 0);
if(i < 1){
break;
}/*if*/
/*Make sure to null the buffer out*/
szBuf[i] = '\0';
p = strstr(szBuf, pszDesc);
if(NULL != p){
ip = p + strlen(pszDesc);
for(j = 0; j < iLen; ip++, j++){
if(isdigit(*ip) || *ip == '.'){
pszBuf[j] = *ip;
}/*if*/
else{
break;
}/*else*/
}/*for*/
pszBuf[j] = '\0';
/*Get out of the loop since we did what we need to do*/
break;
}/*if*/
} while(i > 0 && i != SOCKET_ERROR);
/*Clean up the goodies*/
closesocket(sock);
free(szGET);
WSACleanup();
return pszBuf;
Failure:
closesocket(sock);
free(szGET);
WSACleanup();
return NULL;
}
int main()
{
int szSize = 0;
char szStr[10];
/*Calc the size of the array. Note: This is only valid on arrays not pointer types!*/
szSize = sizeof(szStr) / sizeof(szStr[0]) - 1;
/*Message Box The Outputed Value*/
MessageBox(NULL, GetIP("whatismyip.com", "Your IP Is ", szStr, szSize, 80), "hi", MB_OK);
return 0;
}
Now I am a C++ guy, so you C guys yell at me if I blew anything, I don't think I did though.