Windows c++获取本地ip

int GetLocalIp(vector<string> &vIp)

{

WSADATA wsaData;

int iRet = WSAStartup(((2 << 8) & 0xffff) | (2 & 0xff), &wsaData);

if (iRet != 0) {

std::cerr << "WSAStartup failed: " << iRet << std::endl;

return 1;

}

// 获取本机名

char hostname[256];

int result = gethostname(hostname, sizeof(hostname));

if (result != 0) {

std::cerr << "gethostname failed: " << WSAGetLastError() << std::endl;

WSACleanup();

return 1;

}

// 获取主机信息

struct hostent* phe = gethostbyname(hostname);

if (phe == nullptr) {

std::cerr << "gethostbyname failed: " << WSAGetLastError() << std::endl;

WSACleanup();

return 1;

}

// 遍历所有的IP地址

for (int i = 0; phe->h_addr_list[i] != 0; ++i) {

struct in_addr addr;

memcpy(&addr, phe->h_addr_list[i], sizeof(struct in_addr));

vIp.push_back(inet_ntoa(addr));

std::cout << "Local IP " << i + 1 << ": " << inet_ntoa(addr) << std::endl;

}

WSACleanup();

}

相关推荐
冰茶_18 分钟前
TCP/IP和UDP协议的发展历程
网络·tcp/ip·udp
Yusei_05232 小时前
Linux 进程控制(自用)
linux·windows
秋名RG3 小时前
HTTP 1.0 和 2.0 的区别
网络·网络协议·http
Eugene__Chen3 小时前
内存管理详解(曼波脑图超详细版!)
java·jvm·windows
我不是立达刘宁宇4 小时前
subprocess 模块
windows
不做菜鸟的网工4 小时前
MLAG+VRF防火墙旁挂+双机热备+OSPF部署笔记
网络协议
每天敲200行代码5 小时前
Linux 网络基础(二) (传输协议层:UDP、TCP)
linux·网络·tcp/ip·udp
2301_810154555 小时前
小迪第10天http/s数据包
网络·深度学习·网络协议·安全·web安全·http·网络安全
vortex56 小时前
深入浅出:LDAP 协议全面解析
网络·windows
Edward.W6 小时前
模型上下文协议(MCP)详解
python·网络协议·go·js