码迷,mamicode.com
首页 > 其他好文 > 详细

获取当前操作系统的ip

时间:2018-08-22 18:22:45      阅读:116      评论:0      收藏:0      [点我收藏+]

标签:amp   int   tchar   net   添加   printf   需要   .lib   print   

代码如下:

#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

标签:amp   int   tchar   net   添加   printf   需要   .lib   print   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!