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;
}
View Code
posted @ 2019-12-11 21:05  htj10  阅读(422)  评论(0编辑  收藏  举报
TOP