• 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
    ", WSAGetLastError());
            exit(-1);        //异常退出 
        }
    
        char hostName[256];
        if (gethostname(hostName, sizeof(hostName))) //获取主机名
        {
            printf("Error: %u
    ", WSAGetLastError());
            exit(-1);      //异常退出 
        }
        printf("主机名:             %s
    ", hostName);
    
        hostent *host = gethostbyname(hostName);  // 根据主机名获取主机信息. 
        if (host == NULL)
        {
            printf("Error: %u
    ", 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

    常记溪亭日暮,沉醉不知归路。兴尽晚回舟,误入藕花深处。争渡,争渡,惊起一滩鸥鹭。

    昨夜雨疏风骤,浓睡不消残酒。试问卷帘人,却道海棠依旧。知否?知否?应是绿肥红瘦。
  • 相关阅读:
    一些业内有名的网站收集
    WCF重载
    FCKEditor fckconfig.js配置,添加字体和大小 附:中文字体乱码问题解决
    查询第几条到第几条的数据的SQL语句
    SPOJ 9939 Eliminate the Conflict
    UVA 10534 Wavio Sequence
    HDU 3474 Necklace
    POJ 2823 Sliding Window
    UVA 437 The Tower of Babylon
    UVA 825 Walking on the Safe Side
  • 原文地址:https://www.cnblogs.com/htj10/p/12025126.html
Copyright © 2020-2023  润新知