首页 > 其他 > 详细

获取当前操作系统的ip

时间:2018-08-22 17:46:52      阅读:193      评论:0      收藏:0      [点我收藏+]

代码如下:

#include "stdafx.h"
#include <WinSock2.h>


int get_local_ip() {
    WSADATA wsaData;
    if(WSAStartup(MAKEWORD(2,2),&wsaData))
    {
        return -1;
    }
    char hostname[128];
    int ret = gethostname(hostname, sizeof(hostname));
    if (ret == -1) {
        return -1;
    }
    struct hostent *hent;
    hent = gethostbyname(hostname);
    if (NULL == hent) {
        return -1;
    }
    //直接取h_addr_list列表中的第一个地址h_addr
    char ip[128];
    sprintf_s(ip, "%s", inet_ntoa(*((struct in_addr *)hent->h_addr)));
    printf("%s\n", ip);
    return 0;
}

int _tmain(int argc, _TCHAR* argv[])
{
    get_local_ip();
    system( "PAUSE "); 
	return 0;
}  

注意:

以上程序我使用vs2015编写的,需要在属性中的添加库ws2_32.lib

获取当前操作系统的ip

原文:https://www.cnblogs.com/alinh/p/9519146.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!