zoukankan      html  css  js  c++  java
  • 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

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

    昨夜雨疏风骤,浓睡不消残酒。试问卷帘人,却道海棠依旧。知否?知否?应是绿肥红瘦。
  • 相关阅读:
    A naive AI for TicTacToe
    table font size LaTex
    Python:关于爬虫(2)
    Python:关于爬虫(1)
    RStudio的安装
    Python中安装numpy matplotlib scipy
    python函数编程
    JavaScript的基础语法
    数据结构——线性表的顺序表示(5)
    数据结构——线性表的顺序表示(4)
  • 原文地址:https://www.cnblogs.com/htj10/p/12025126.html
Copyright © 2011-2022 走看看