vc 获取本机IP
bool GetPublicIP(char* szBuffer)
{
if (NULL == szBuffer)
{
return false;
}
const int nBufSize = 256;
char chBuf[nBufSize];
ZeroMemory(chBuf, nBufSize);
WSAData wsaDat;
short int Port = 80;
WSAStartup(MAKEWORD(2, 2), &wsaDat);
SOCKET sd = socket(AF_INET, SOCK_STREAM, 0);
if (INVALID_SOCKET == sd)
{
return false;
}
SOCKADDR_IN sockAddr;
memset((void*)&sockAddr, 0, sizeof(sockAddr));
sockAddr.sin_family = AF_INET;
sockAddr.sin_port = htons(Port);
sockAddr.sin_addr.s_addr = inet_addr(m_szTargetAddress[0]);
if ((connect(sd, (LPSOCKADDR)&sockAddr, sizeof(sockAddr))) == SOCKET_ERROR)
{
return false;
}
char sendstr[] = "GET /ip2city.asp HTTP/1.1\r\nAccept: */*\r\nReferer: ******\r\nUser-Agent: Mozilla/4.0\r\nHost: www.ip138.com\r\nConnection: close\r\n\r\n\0";
char* p = sendstr;
int iLen = strlen(sendstr);
while (iLen)
{
int iRet = send(sd, p, iLen, 0);
if (iRet > 0)
{
p += iRet;
iLen -= iRet;
continue;
}
return false;
}
char recvstr[1024];
memset(recvstr, 0, 1024);
p = recvstr;
char* iIndex_Head;
iLen = 1024;
int need_len = -1;
while (iLen)
{
int iRet = recv(sd, p, iLen, 0);
if (iRet <= 0)
{
return false;
}
p += iRet;
iLen -= iRet;
if ((iIndex_Head = strstr(recvstr, "\r\n\r\n")) && (need_len == -1))
{
char* iIndex = strstr(recvstr, "Content-Length:");
if (!iIndex)
{
continue;
}
char *p1 = iIndex + lstrlen("Content-Length:");
need_len = iIndex_Head - recvstr + 2 + atol(p1);
}
if (1024 - iLen >= need_len)
{
break;
}
}
char *p1 = strstr(iIndex_Head, "[");
char *p0 = strstr(p1, "]");
*p0 = '\0';
closesocket(sd);
WSACleanup();
lstrcpy(szBuffer, p1 + 1);
return true;
}