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

获取本机IP及在本机IP的基础上自增1(只针对有一个IP的机器)

时间:2018-02-24 10:43:00      阅读:128      评论:0      收藏:0      [点我收藏+]

标签:ip地址   etc   tla   主机   span   获取本机ip   ali   class   本地ip   

1、获取本机IP

 1 char* getLocalIP()
 2 {
 3     WSADATA wsaData;
 4     int err = WSAStartup(MAKEWORD(2, 0), &wsaData);
 5     if (err != 0)
 6     {
 7         OUTINFO_1_PARAM("ASTSWSAStartup执行错误%d\n",err);
 8         return NULL;
 9     }
10     //获取主机名
11     char szHostName[256] = {0};
12     int nRetCode;
13     nRetCode = gethostname(szHostName,sizeof(szHostName) );
14     if (nRetCode != 0)
15     {
16         OUTINFO_0_PARAM("ASTS获取主机名称失败\n");
17         WSAGetLastError(); 
18         WSACleanup();
19         return NULL; 
20     }
21 
22     //获取本机IP
23     char* lpLocalIP;
24     PHOSTENT hostinfo;
25     hostinfo = gethostbyname(szHostName);
26     if (hostinfo != NULL)
27     {
28         lpLocalIP = inet_ntoa(*(struct in_addr*)*hostinfo->h_addr_list);
29         OUTINFO_1_PARAM("ASTS主机名: %s\n", szHostName);
30         OUTINFO_1_PARAM("ASTS本地IP: %s\n", lpLocalIP);
31 
32         WSACleanup();
33         return lpLocalIP;
34     }
35     else
36     {
37         WSACleanup();
38         return NULL;
39     }
40 }

2、获取本机IP并在本机IP的基础上增加1

 1 char* getAddOneIP()
 2 {
 3     WSADATA wsaData;
 4     int err = WSAStartup(MAKEWORD(2, 0), &wsaData);
 5     if (err != 0)
 6     {
 7         OUTINFO_1_PARAM("ASTSWSAStartup执行错误%d\n",err);
 8         return NULL;
 9     }
10     //获取主机名
11     char szHostName[256] = {0};
12     int nRetCode;
13     nRetCode = gethostname(szHostName,sizeof(szHostName) );
14     if (nRetCode != 0)
15     {
16         OUTINFO_0_PARAM("ASTS获取主机名称失败\n");
17         WSAGetLastError(); 
18         WSACleanup();
19         return NULL; 
20     }
21 
22     //获取本机IP
23     char* lpLocalIP;
24     PHOSTENT hostinfo;
25     hostinfo = gethostbyname(szHostName);
26     if (hostinfo != NULL)
27     {
28         lpLocalIP = inet_ntoa(*(struct in_addr*)*hostinfo->h_addr_list);
29         OUTINFO_1_PARAM("ASTS主机名: %s\n", szHostName);
30         OUTINFO_1_PARAM("ASTS本地IP: %s\n", lpLocalIP);
31 
32         struct in_addr nextIP = {0};
33         memcpy(&nextIP, *hostinfo->h_addr_list, sizeof(nextIP));
34         nextIP.s_impno ++;        //下一个IP
35         char * lpNextIP = inet_ntoa(nextIP);
36         OUTINFO_1_PARAM("ASTS返回出去的IP地址: %s\n", lpNextIP);
37         WSACleanup();
38         return lpNextIP;
39     }
40     else
41     {
42         WSACleanup();
43         return NULL;
44     }
45 }

 

获取本机IP及在本机IP的基础上自增1(只针对有一个IP的机器)

标签:ip地址   etc   tla   主机   span   获取本机ip   ali   class   本地ip   

原文地址:https://www.cnblogs.com/LYF-LIUDAO/p/8464023.html

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