GetLocalIp

/** * @file GetLocalIp.cpp * @brief 从本地计算机取IP, 适用于单网卡, 多网卡没试验 * @note * 字符集 _UNICODE, 用于工程后期的国际化 * /MTd 编译选项(DLL静态编译进工程), 用于程序发布 * goto 仅用于函数内部的错误返回处理, 用于保证单入单出 * 工程输出在Z盘, Z盘用subst模拟. * * LNK4199警告的去除: Property >> Configuration Properties >> Linker >> Input * >> Delay Loaded DLLs >> $(NOINHERIT) */ #include "stdafx.h" #include "targetver.h" #include <Winsock2.h> /**< Winsock2.h 要包在 windows.h 之前, 避免编译错误 */ #pragma comment(lib, "Ws2_32.lib") #include <windows.h> #include <atlbase.h> // for A2W #include <atlconv.h> #include <vector> // for std #ifdef _UNICODE #define tstring std::wstring //其实总是在用 std::wstring #else #define tstring std::string #endif INT GetLocalIp(tstring & strIp); int _tmain(int argc, _TCHAR* argv[]) { tstring strIp; if(S_OK == GetLocalIp(strIp)) { _tprintf(_T("LocalIp = [%s]/n"), strIp.c_str()); } else { _tprintf(_T("[Failed]GetLocalIp()/n")); } /** * run results * LocalIp = [192.168.52.128] */ getchar(); return 0; } INT GetLocalIp(tstring & strIp) { INT iRc = S_OK; INT wsa_Rc = 0; CHAR szHostName[MAX_PATH]; CHAR * szLocalIP = NULL; struct hostent * host_entry = NULL; WSADATA wsa_Data; USES_CONVERSION; ZeroMemory(szHostName, sizeof(szHostName)); strIp = _T("127.0.0.1"); /**< 失败时, 返回127.0.0.1 */ /** * 试验证明, WSAStartup和WSACleanup的成对使用, * 并不影响主程序中的socket操作 */ WSAStartup(MAKEWORD(2,2), &wsa_Data); gethostname(szHostName, MAX_PATH); host_entry = gethostbyname(szHostName); if(!host_entry) { iRc = S_FALSE; goto _GetLocalIp_End; } szLocalIP = inet_ntoa(*(struct in_addr *)*host_entry->h_addr_list); strIp = A2W(szLocalIP); WSACleanup(); _GetLocalIp_End: return iRc; }

你可能感兴趣的:(properties,vector,socket,Path,delay,linker)