在Windows平台下,可以使用以下方法获取本机的IP地址:
#include <iostream>
#include <winsock2.h>
#include <iphlpapi.h>
#pragma comment(lib, "ws2_32.lib")
#pragma comment(lib, "iphlpapi.lib")
int main() {
WSADATA wsaData;
if (WSAStartup(MAKEWORD(2, 2), &wsaData) != 0) {
std::cerr << "Failed to initialize Winsock." << std::endl;
return 1;
}
DWORD bufferLength = 15000; // 假设缓冲区长度为15000
PIP_ADAPTER_ADDRESSES adapterAddresses = nullptr;
// 获取适配器地址信息
ULONG result = GetAdaptersAddresses(AF_UNSPEC, GAA_FLAG_INCLUDE_PREFIX, NULL,
adapterAddresses, &bufferLength);
if (result == ERROR_BUFFER_OVERFLOW) {
// 分配足够大的内存
adapterAddresses = reinterpret_cast<PIP_ADAPTER_ADDRESSES>(new BYTE[bufferLength]);
result = GetAdaptersAddresses(AF_UNSPEC, GAA_FLAG_INCLUDE_PREFIX, NULL,
adapterAddresses, &bufferLength);
}
if (result == NO_ERROR) {
PIP_ADAPTER_ADDRESSES adapter = adapterAddresses;
while (adapter != nullptr) {
// 可以通过 adapter->AdapterName 来获取适配器名称
// 遍历适配器的多个IP地址
for (PIP_ADAPTER_UNICAST_ADDRESS unicastAddress = adapter->FirstUnicastAddress;
unicastAddress != nullptr; unicastAddress = unicastAddress->Next) {
sockaddr* address = unicastAddress->Address.lpSockaddr;
// 判断是否是IPv4地址
if (address->sa_family == AF_INET) {
char ipBuffer[INET_ADDRSTRLEN];
inet_ntop(AF_INET, &reinterpret_cast<sockaddr_in*>(address)->sin_addr,
ipBuffer, INET_ADDRSTRLEN);
std::cout << "Interface: " << adapter->Description
<< ", Address: " << ipBuffer << std::endl;
}
}
adapter = adapter->Next;
}
} else {
std::cerr << "Failed to get IP addresses: " << result << std::endl;
}
if (adapterAddresses != nullptr) {
delete[] reinterpret_cast<BYTE*>(adapterAddresses);
}
WSACleanup();
return 0;
}
以上代码会输出本机的所有活动的IPv4地址。需要注意的是,需要包含头文件 <iostream>
, <winsock2.h>
, <iphlpapi.h>
,并链接 ws2_32.lib
和 iphlpapi.lib
库。
编译时可以使用以下命令:
g++ -o getip getip.cpp -lws2_32 -liphlpapi
运行生成的可执行文件 getip
即可查看本机的IP地址信息。
内容由零声教学AI助手提供,问题来源于学员提问