C++获取主机的IP
1. 参考https://www.cnblogs.com/LyShark/p/9158555.html
#include<winsock2.h> //该头文件需在windows.h之前 #include<windows.h> //#include<string> #include<iostream> #pragma comment(lib,"ws2_32.lib") using namespace std; void getIP() { WSADATA WSAData; //WSADATA结构被用来储存调用AfxSocketInit全局函数返回的Windows Sockets初始化信息。 if (WSAStartup(MAKEWORD(2, 0), &WSAData)) // 初始化Windows sockets API { printf("WSAStartup failed %s\n", WSAGetLastError()); exit(-1); //异常退出 } char hostName[256]; if (gethostname(hostName, sizeof(hostName))) //获取主机名 { printf("Error: %u\n", WSAGetLastError()); exit(-1); //异常退出 } printf("主机名: %s\n", hostName); hostent *host = gethostbyname(hostName); // 根据主机名获取主机信息. if (host == NULL) { printf("Error: %u\n", WSAGetLastError()); exit(-1); } cout << "主机地址类型: " << host->h_addrtype << endl << "地址清单: " << host->h_addr_list << endl << "别名列表: " << host->h_aliases << endl << "地址长度: " << host->h_length << endl << "正式的主机名: " << host->h_name << endl; for (int i = 0; host->h_addr_list[i] != 0; i++) { std::string s = inet_ntoa(*(struct in_addr*)host->h_addr_list[i]) ; } WSACleanup(); } int main() { getIP(); return 0; }
常记溪亭日暮,沉醉不知归路。兴尽晚回舟,误入藕花深处。争渡,争渡,惊起一滩鸥鹭。
昨夜雨疏风骤,浓睡不消残酒。试问卷帘人,却道海棠依旧。知否?知否?应是绿肥红瘦。