使用C++显示连接到网络的设备的名称和IP地址可以通过以下步骤实现:
#include <iostream>
#include <string>
#include <vector>
#include <winsock2.h>
#include <iphlpapi.h>
#pragma comment(lib, "iphlpapi.lib")
#pragma comment(lib, "ws2_32.lib")
void GetNetworkDevices(std::vector<std::string>& deviceNames, std::vector<std::string>& ipAddresses) {
// 初始化Winsock
WSADATA wsaData;
if (WSAStartup(MAKEWORD(2, 2), &wsaData) != 0) {
std::cout << "Failed to initialize Winsock." << std::endl;
return;
}
// 获取网络接口信息
ULONG bufferSize = 0;
if (GetAdaptersAddresses(AF_UNSPEC, GAA_FLAG_INCLUDE_PREFIX, nullptr, nullptr, &bufferSize) == ERROR_BUFFER_OVERFLOW) {
IP_ADAPTER_ADDRESSES* adapterAddresses = reinterpret_cast<IP_ADAPTER_ADDRESSES*>(new char[bufferSize]);
if (GetAdaptersAddresses(AF_UNSPEC, GAA_FLAG_INCLUDE_PREFIX, nullptr, adapterAddresses, &bufferSize) == NO_ERROR) {
IP_ADAPTER_ADDRESSES* adapter = adapterAddresses;
while (adapter != nullptr) {
// 获取设备名称
std::string deviceName = adapter->FriendlyName;
deviceNames.push_back(deviceName);
// 获取IP地址
IP_ADAPTER_UNICAST_ADDRESS* unicastAddress = adapter->FirstUnicastAddress;
while (unicastAddress != nullptr) {
sockaddr* address = unicastAddress->Address.lpSockaddr;
if (address->sa_family == AF_INET) {
sockaddr_in* ipv4Address = reinterpret_cast<sockaddr_in*>(address);
char ipAddress[INET_ADDRSTRLEN];
inet_ntop(AF_INET, &(ipv4Address->sin_addr), ipAddress, INET_ADDRSTRLEN);
ipAddresses.push_back(ipAddress);
}
unicastAddress = unicastAddress->Next;
}
adapter = adapter->Next;
}
}
delete[] reinterpret_cast<char*>(adapterAddresses);
}
// 清理Winsock
WSACleanup();
}
int main() {
std::vector<std::string> deviceNames;
std::vector<std::string> ipAddresses;
GetNetworkDevices(deviceNames, ipAddresses);
for (size_t i = 0; i < deviceNames.size(); ++i) {
std::cout << "Device Name: " << deviceNames[i] << std::endl;
std::cout << "IP Address: " << ipAddresses[i] << std::endl;
std::cout << std::endl;
}
return 0;
}
这样,运行程序后,就可以显示连接到网络的设备的名称和IP地址了。
请注意,以上代码是基于Windows平台的实现。如果在其他操作系统上运行,可能需要进行相应的修改。此外,该代码仅获取IPv4地址,如果需要获取IPv6地址,可以进行相应的扩展。
领取专属 10元无门槛券
手把手带您无忧上云