标签:c style class code tar http
#include "stdafx.h" #include <WINSOCK2.H> #include <urlmon.h> #pragma comment(lib, "ws2_32.lib") #pragma comment(lib, "urlmon.lib") #define MAX_SIZE 1024 int GetLocalIP(); int GetInternetIP(); int main(int argc, char* argv[]) { GetLocalIP(); GetInternetIP(); return 0; } int GetLocalIP() { WSADATA wsaData; int err = WSAStartup(MAKEWORD(2, 0), &wsaData); if (err != 0) { return err; } char szHostName[MAX_PATH] = {0}; int nRetCode; nRetCode = gethostname(szHostName, sizeof(szHostName)); char* lpLocalIP; PHOSTENT hostinfo; if (nRetCode != 0) { return WSAGetLastError(); } hostinfo = gethostbyname(szHostName); lpLocalIP = inet_ntoa(*(struct in_addr*)*hostinfo->h_addr_list); if (szHostName != NULL) { printf("主机名: %s\n", szHostName); printf("本地IP: %s\n", lpLocalIP); } WSACleanup(); return 0; } int GetInternetIP() { char buf[MAX_PATH] = {0}; //把网页中读出的数据放在此处 char chTempIp[128] = {0}; char chIP[64] = {0}; //最终存放IP在此 //将网页数据写入c:\i.ini文件中 URLDownloadToFile(0, "http://iframe.ip138.com/ic.asp", "c:\\i.ini", 0, NULL); FILE *fp = fopen("c:\\i.ini", "r"); if (fp != NULL) { // fseek(fp, 0, SEEK_SET); fread(buf, 1, MAX_PATH, fp); fclose(fp); //在buf中查找 [ 的位置, iIndex是buf中从[开始剩下的字符串,包括[这个字符串 char* iIndex = strstr(buf, "["); if (iIndex) { sprintf(chTempIp, "%s", iIndex); int nBuflen = strlen(chTempIp); for (int i = 0; i < nBuflen; i++) { chIP[i] = chTempIp[i+1]; //如果发现有 ] 则截断 if (chTempIp[i] == ‘]‘) { chIP[i-1] = ‘\0‘; //printf("外网IP: %s\n", chIP); } } } } printf("外网IP: %s\n", chIP); remove("c:\\i.ini"); return 0; }
C++实现获取本机机器名及外网IP代码,布布扣,bubuko.com
标签:c style class code tar http
原文地址:http://www.cnblogs.com/lizs/p/3757696.html