要在C++中獲取本機IP地址,可以使用如下方法:
#include <iostream>
#include <string>
#include <winsock2.h>
#include <ws2tcpip.h>
#pragma comment(lib, "ws2_32.lib")
int main() {
WSADATA wsaData;
if (WSAStartup(MAKEWORD(2, 2), &wsaData) != 0) {
std::cerr << "WSAStartup failed" << std::endl;
return 1;
}
char hostname[256];
if (gethostname(hostname, sizeof(hostname)) == SOCKET_ERROR) {
std::cerr << "Error getting hostname" << std::endl;
WSACleanup();
return 1;
}
struct addrinfo* result = NULL;
struct addrinfo hints;
ZeroMemory(&hints, sizeof(hints));
hints.ai_family = AF_INET;
hints.ai_socktype = SOCK_STREAM;
hints.ai_protocol = IPPROTO_TCP;
if (getaddrinfo(hostname, NULL, &hints, &result) != 0) {
std::cerr << "Error getting address info" << std::endl;
WSACleanup();
return 1;
}
struct sockaddr_in* addr = (struct sockaddr_in*) result->ai_addr;
char ip[INET_ADDRSTRLEN];
inet_ntop(AF_INET, &addr->sin_addr, ip, sizeof(ip));
std::cout << "Hostname: " << hostname << std::endl;
std::cout << "IP Address: " << ip << std::endl;
freeaddrinfo(result);
WSACleanup();
return 0;
}
這段代碼首先初始化Winsock庫,然后使用gethostname
函數獲取本地主機名,接著使用getaddrinfo
函數獲取主機地址信息,最后通過inet_ntop
函數將sockaddr_in
結構體中的IP地址轉換為字符串格式并輸出。