要在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地址转换为字符串格式并输出。