C++如何获取本机IP地址,可以通过以下步骤实现:
- 加载网络库
为了使用网络相关的库函数,需要在程序中加载网络库。可以在程序中包含Winsock2.h头文件,并添加相应的库路径和库文件,如下所示:
#include <Winsock2.h>
#pragma comment(lib, "ws2_32.lib")
- 初始化Winsock
在使用Winsock之前,需要初始化它。可以调用WSAStartup函数进行初始化,如下所示:
WSADATA wsaData;
int result = WSAStartup(MAKEWORD(2, 2), &wsaData);
if (result != 0) {
printf("WSAStartup failed: %d\n", result);
return 1;
}
- 调用gethostname获取主机名
主机名是本机的唯一标识符,可以通过调用gethostname函数来获取它,如下所示:
char hostname[256];
if (gethostname(hostname, sizeof(hostname)) == SOCKET_ERROR) {
printf("Failed to get hostname: %d\n", WSAGetLastError());
WSACleanup();
return 1;
}
- 调用gethostbyname获取IP地址
获取主机名后,可以通过调用gethostbyname函数来获取IP地址,如下所示:
struct hostent* host;
host = gethostbyname(hostname);
if (host == NULL) {
printf("Failed to get IP address: %d\n", WSAGetLastError());
WSACleanup();
return 1;
}
char* ip = inet_ntoa(*(struct in_addr*)*host->h_addr_list);
printf("IP address: %s\n", ip);
完整示例代码如下所示:
#include <stdio.h>
#include <Winsock2.h>
#pragma comment(lib, "ws2_32.lib")
int main() {
WSAData wsaData;
int result = WSAStartup(MAKEWORD(2, 2), &wsaData);
if (result != 0) {
printf("WSAStartup failed: %d\n", result);
return 1;
}
char hostname[256];
if (gethostname(hostname, sizeof(hostname)) == SOCKET_ERROR) {
printf("Failed to get hostname: %d\n", WSAGetLastError());
WSACleanup();
return 1;
}
struct hostent* host;
host = gethostbyname(hostname);
if (host == NULL) {
printf("Failed to get IP address: %d\n", WSAGetLastError());
WSACleanup();
return 1;
}
char* ip = inet_ntoa(*(struct in_addr*)*host->h_addr_list);
printf("IP address: %s\n", ip);
WSACleanup();
return 0;
}
示例1:
假设本机主机名为"MyComputer",运行程序后可以得到输出结果:
IP address: 192.168.0.123
示例2:
将主机名定义为字符串常量,程序如下所示:
#include <stdio.h>
#include <Winsock2.h>
#pragma comment(lib, "ws2_32.lib")
int main() {
WSAData wsaData;
int result = WSAStartup(MAKEWORD(2, 2), &wsaData);
if (result != 0) {
printf("WSAStartup failed: %d\n", result);
return 1;
}
const char* hostname = "MyComputer";
struct hostent* host;
host = gethostbyname(hostname);
if (host == NULL) {
printf("Failed to get IP address: %d\n", WSAGetLastError());
WSACleanup();
return 1;
}
char* ip = inet_ntoa(*(struct in_addr*)*host->h_addr_list);
printf("IP address: %s\n", ip);
WSACleanup();
return 0;
}
运行程序后可以得到输出结果:
IP address: 192.168.0.123
本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:C++如何获取本机的IP地址 - Python技术站