C/C++ 获取本机IP地址信息

#include<winsock2.h>  
#include<iostream>  
#include<string>
using namespace std;
#pragma comment(lib, "WS2_32.lib")

string getIP()
{
    WSADATA WSAData;
    char hostName[256];
    if (!WSAStartup(MAKEWORD(2, 0),&WSAData))
    {  
        if(!gethostname(hostName,sizeof(hostName)))
        {
            hostent *host=gethostbyname(hostName);
            if(host!=NULL)
            {
                return inet_ntoa(*(struct in_addr*)*host->h_addr_list);
            }
        }
    }      
    return "Get IP failed.";  
}

int main()
{
    cout<<"IP地址为:"<<getIP()<<endl;
    system("pause");
    return 0;   
}
posted @ 2018-06-09 09:55  lyshark  阅读(1659)  评论(0编辑  收藏  举报

loading... | loading...
博客园 - 开发者的网上家园