windows C++获得本地IP地址

来源:互联网 发布:lol for mac国服 编辑:程序博客网 时间:2024/05/18 13:09
#include <iostream> #include <Winsock2.h> using namespace std;string GetLocalIpAddress(){WORD wVersionRequested = MAKEWORD(2, 2);WSADATA wsaData;if (WSAStartup(wVersionRequested, &wsaData) != 0)return "";char local[255] = {0};gethostname(local, sizeof(local));hostent* ph = gethostbyname(local);if (ph == NULL)return "";in_addr addr;memcpy(&addr, ph->h_addr_list[0], sizeof(in_addr)); // 这里仅获取第一个ipstring localIP;localIP.assign(inet_ntoa(addr));WSACleanup();return localIP;}void main(){ char date[100]; strcpy (date, const_cast<char*>(GetLocalIpAddress().c_str())); cout<<date<<endl; system("PAUSE");}
确保构建环境的连接器依赖项包含了WS2_32.lib,使用Winsock的程序必须连接此文件