#include <winsock2.h> #include <string> #include <boost/filesystem.hpp> #pragma comment(lib,"ws2_32.lib") std::string GetLocalIpAndSave(void) { WSADATA wsaData; char name[155]; std::string strIp; PHOSTENT hostinfo; if ( WSAStartup( MAKEWORD(2,0), &wsaData ) == 0 ) { if( gethostname ( name, sizeof(name)) == 0) { //获取机器名 if((hostinfo = gethostbyname(name)) != NULL) { //这些就是获得IP的函数 strIp = inet_ntoa (*(struct in_addr *)*hostinfo->h_addr_list); //获取本机ip } } WSACleanup( ); } CHAR path[MAX_PATH] = {0}; GetModuleFileNameA(NULL, path, MAX_PATH); boost::filesystem::path fpath(path); fpath = fpath.parent_path(); fpath /= "serverip.txt"; FILE* f = fopen(fpath.string().c_str(), "wb+"); fwrite(PVOID(strIp.c_str()), strIp.size(), 1, f); fclose(f); return strIp;//返回本机ip }
原文:http://blog.csdn.net/qingzai_/article/details/45174219