首先,这篇文章实现了两种方法查询IP,实现截图如下:

第一种方法时调用系统命令,代码如下:

#include <cstdlib>
#include <iostream>
using namespace std;
int main(int argc, char *argv[])
{
system("ipconfig");
system("PAUSE");
return EXIT_SUCCESS;
}

下面这种方法是对源码的解析:

#include <windows.h>
#include <IPHlpApi.h>
#include <stdio.h>
#include <time.h>
#include<Ipexport.h>
#include<Windns.h>
#pragma comment(lib,"Ws2_32")
#pragma comment(lib,"Dnsapi")
#define Max 10 ;
//#include <winsock2.h>
#pragma comment(lib,"IPHlpApi")
void DoUsage(bool);
void DoRelease(bool);// realized
void DoRenew(bool);//realized
void DoDisplayDns(bool);
void DoFlushDns(bool);
void DoAll(void);
void GetInterfaceInfo(void);
//LPCTSTR GetNodeTypeName(UINT nodeType);
//LPCTSTR GetInterfaceTypeName(UINT InterfaceType);
IP_ADAPTER_INDEX_MAP adapterInfo;
PIP_INTERFACE_INFO pInfo;
DWORD checkReturn;
void main(int argc,char **argv)
{
bool doUsage=false;
bool doAll=false;
bool doRelease=false;
bool doRenew=false;
bool doDisplayDns=false;
bool doFlushDns=false;
char *argument; //store the command line code
argument=&argv[][]; if((argc>)&&(argv[][]=='/'))
{
if(!strcmp(argument,"?"))
{
doUsage=true;
DoUsage(doUsage);
}
if(!strcmp(argument,"all"))
{
doUsage=true;
DoAll(); } if(!strcmp(argument,"release"))
{
doRelease=true;
DoRelease(doRelease);
} if(!strcmp(argument,"renew"))
{
doRenew=true;
DoRenew(doRenew); } if(!strcmp(argument,"displaydns"))
{
doDisplayDns=true;
DoDisplayDns(doDisplayDns); } if(!strcmp(argument,"flushdns"))
{
doFlushDns=true;
DoFlushDns(doFlushDns); } }
else
printf("error command code!");
printf("......................................"); } /* get the using adapter information*/ void GetInterfaceInfo()
{ ULONG outBufferLen=;
pInfo=(IP_INTERFACE_INFO *)malloc(sizeof(IP_INTERFACE_INFO));
/* Make the first call to buffer information*/
if((checkReturn=GetInterfaceInfo(pInfo,&outBufferLen))==ERROR_INSUFFICIENT_BUFFER)
{
free(pInfo);
pInfo=(IP_INTERFACE_INFO *)malloc(outBufferLen); } /* Make the second call of GetInterfaceInfo() to get the actual data */ if((checkReturn=GetInterfaceInfo(pInfo,&outBufferLen))==NO_ERROR)
{
adapterInfo=pInfo->Adapter[];//关键此处返回IP_ADAPTER_INDEX_MAP 用于IP更新
printf("the dapter name is: %d ",pInfo->Adapter[].Name); }
else
{ printf("Get the interface information occer error!"); } } /* release IP address */ void DoRelease(bool doRelease)
{
if(doRelease)
{ GetInterfaceInfo();
/**the specific action to config/release*/
if((checkReturn=IpReleaseAddress(&adapterInfo))==NO_ERROR)
{
printf("the action of release IP work!");
}
else
printf("An error occured while releasing interface of %s",pInfo->Adapter[].Name); }
else
{
printf("illegal action"); } } /** Do renew IPAddree */ void DoRenew(bool doRenew)
{ if(doRenew)
{
GetInterfaceInfo(); if((checkReturn=IpRenewAddress(&adapterInfo))==NO_ERROR)
{
printf("the action of release IP work!");
}
else
printf("An error occured while releasing interface of %s",pInfo->Adapter[].Name); } else
{
printf("illegal action"); }
} /* display all information ipconfig/all */ void DoAll(void) { DWORD returnCheckError;
PFIXED_INFO pFixedInfo;
DWORD FixedInfoSize = ; PIP_ADDR_STRING pAddrStr;
PIP_ADAPTER_INFO pAdapt,pAdapterInfo; if ((returnCheckError = GetNetworkParams(NULL, &FixedInfoSize)) != )
{
if (returnCheckError != ERROR_BUFFER_OVERFLOW)
{
printf("GetNetworkParams sizing failed with error %d\n", returnCheckError);
return;
}
} // Allocate memory from sizing information
if ((pFixedInfo = (PFIXED_INFO) malloc( FixedInfoSize)) == NULL)
{
printf("Memory allocation error\n");
return;
} if ((returnCheckError = GetNetworkParams(pFixedInfo, &FixedInfoSize)) == )
{
printf("\tHost Name . . . . . . . . . : %s\n", pFixedInfo->HostName);
printf("\tDNS Servers . . . . . . . . : %s\n", pFixedInfo->DnsServerList.IpAddress.String);
pAddrStr = pFixedInfo->DnsServerList.Next;
while(pAddrStr)
{
printf("%52s\n", pAddrStr->IpAddress.String);
pAddrStr = pAddrStr->Next;
} printf("\tNode Type . . . . . . . . . : ");
switch (pFixedInfo->NodeType)
{
case :
printf("%s\n", "Broadcast");
break;
case :
printf("%s\n", "Peer to peer");
break;
case :
printf("%s\n", "Mixed");
break;
case :
printf("%s\n", "Hybrid");
break;
default:
printf("\n");
} printf("\tNetBIOS Scope ID. . . . . . : %s\n", pFixedInfo->ScopeId);
printf("\tIP Routing Enabled. . . . . : %s\n", (pFixedInfo->EnableRouting ? "yes" : "no"));
printf("\tWINS Proxy Enabled. . . . . : %s\n", (pFixedInfo->EnableProxy ? "yes" : "no"));
printf("\tNetBIOS Resolution Uses DNS : %s\n", (pFixedInfo->EnableDns ? "yes" : "no"));
} else
{
printf("GetNetworkParams failed with error %d\n", returnCheckError);
return;
} //
// Enumerate all of the adapter specific information using the IP_ADAPTER_INFO structure.
// Note: IP_ADAPTER_INFO contains a linked list of adapter entries. ULONG AdapterInfoSize = ;
if ((returnCheckError = GetAdaptersInfo(NULL, &AdapterInfoSize)) != )
{
if (returnCheckError != ERROR_BUFFER_OVERFLOW)
{
printf("GetAdaptersInfo sizing failed with error %d\n", returnCheckError);
return;
}
} // Allocate memory from sizing information
if ((pAdapterInfo = (PIP_ADAPTER_INFO) GlobalAlloc(GPTR, AdapterInfoSize)) == NULL)
{
printf("Memory allocation error\n");
return;
} // Get actual adapter information
if ((returnCheckError = GetAdaptersInfo(pAdapterInfo, &AdapterInfoSize)) != )
{
printf("GetAdaptersInfo failed with error %d\n", returnCheckError);
return;
} pAdapt = pAdapterInfo; while (pAdapt)
{
switch (pAdapt->Type)
{
case MIB_IF_TYPE_ETHERNET:
printf("\nEthernet adapter ");
break;
case MIB_IF_TYPE_TOKENRING:
printf("\nToken Ring adapter ");
break;
case MIB_IF_TYPE_FDDI:
printf("\nFDDI adapter ");
break;
case MIB_IF_TYPE_PPP:
printf("\nPPP adapter ");
break;
case MIB_IF_TYPE_LOOPBACK:
printf("\nLoopback adapter ");
break;
case MIB_IF_TYPE_SLIP:
printf("\nSlip adapter ");
break;
case MIB_IF_TYPE_OTHER:
default:
printf("\nOther adapter ");
}
printf("%s:\n\n", pAdapt->AdapterName); printf("\tDescription . . . . . . . . : %s\n", pAdapt->Description); printf("\tPhysical Address. . . . . . : ");
for (UINT i=; i<pAdapt->AddressLength; i++)
{
if (i == (pAdapt->AddressLength - ))
printf("%.2X\n",(int)pAdapt->Address[i]);
else
printf("%.2X-",(int)pAdapt->Address[i]);
} printf("\tDHCP Enabled. . . . . . . . : %s\n", (pAdapt->DhcpEnabled ? "yes" : "no")); pAddrStr = &(pAdapt->IpAddressList);
while(pAddrStr)
{
printf("\tIP Address. . . . . . . . . : %s\n", pAddrStr->IpAddress.String);
printf("\tSubnet Mask . . . . . . . . : %s\n", pAddrStr->IpMask.String);
pAddrStr = pAddrStr->Next;
} printf("\tDefault Gateway . . . . . . : %s\n", pAdapt->GatewayList.IpAddress.String);
pAddrStr = pAdapt->GatewayList.Next;
while(pAddrStr)
{
printf("%52s\n", pAddrStr->IpAddress.String);
pAddrStr = pAddrStr->Next;
} printf("\tDHCP Server . . . . . . . . : %s\n", pAdapt->DhcpServer.IpAddress.String);
printf("\tPrimary WINS Server . . . . : %s\n", pAdapt->PrimaryWinsServer.IpAddress.String);
printf("\tSecondary WINS Server . . . : %s\n", pAdapt->SecondaryWinsServer.IpAddress.String); struct tm *newtime; // Display coordinated universal time - GMT
newtime = gmtime(&pAdapt->LeaseObtained);
printf( "\tLease Obtained. . . . . . . : %s", asctime( newtime ) ); newtime = gmtime(&pAdapt->LeaseExpires);
printf( "\tLease Expires . . . . . . . : %s", asctime( newtime ) ); pAdapt = pAdapt->Next;
}
} void DoUsage(bool doUsage)
{ if(doUsage)
{
printf("\nUSAGE:\n"
" ipconfig [/? | /all | /renew [adapter] | /release [adapter] |\n"
" /flushdns | /displaydns | /registerdns |\n"
" /showclassid adapter |\n"
" /setclassid adapter [classid] ]\n"
"\n"
"where\n"
" adapter Connection name\n"
" (wildcard characters * and ? allowed, see examples)\n"
"\n"
" Options:\n"
" /? Display this help message\n"
" /all Display full configuration information.\n"
" /release Release the IP address for the specified adapter.\n"
" /renew Renew the IP address for the specified adapter.\n"
" /flushdns Purges the DNS Resolver cache.\n"
" /registerdns Refreshes all DHCP leases and re-registers DNS names.\n"
" /displaydns Display the contents of the DNS Resolver Cache.\n"
" /showclassid Displays all the dhcp class IDs allowed for adapter.\n"
" /setclassid Modifies the dhcp class id.\n"
"\n"
"The default is to display only the IP address, subnet mask and\n"
"default gateway for each adapter bound to TCP/IP.\n"
"\n"
"For Release and Renew, if no adapter name is specified, then the IP address\n"
"leases for all adapters bound to TCP/IP will be released or renewed.\n"
"\n"
"For Setclassid, if no ClassId is specified, then the ClassId is removed.\n"
"\n"
"Examples:\n"
" > ipconfig ... Show information.\n"
" > ipconfig /all ... Show detailed information\n"
" > ipconfig /renew ... renew all adapters\n"
" > ipconfig /renew EL* ... renew any connection that has its\n"
" name starting with EL\n"
" > ipconfig /release *Con* ... release all matching connections,\n"
" eg. \"Local Area Connection 1\" or\n"
" \"Local Area Connection 2\"\n"); } else
{
printf("ilegal code!"); } }
void DoDisplayDns(bool doDisplayDns) {
if(doDisplayDns)
{
char hostname[];
int iRet = ;
WSADATA wsaData; DNS_STATUS status; //Return value of DnsQuery_A() function.
PDNS_RECORD pDnsRecord;
int assignBuffLenght;
assignBuffLenght=(sizeof(DNS_RECORD))*Max;
pDnsRecord=(DNS_RECORD*)malloc(assignBuffLenght);
memset(pDnsRecord,,assignBuffLenght); if (WSAStartup(MAKEWORD(,),&wsaData)) //调用Windows Sockets DLL
{
printf("Winsock无法初始化!\n");
WSACleanup(); } memset(hostname, , );
iRet = gethostname(hostname, sizeof(hostname));
if(iRet != )
{
printf( "get hostname error:%d\n", iRet);
}
printf("%s\n", hostname); LPSTR pOwnerName=hostname; // Calling function DnsQuery to query Host or PTR records
status = DnsQuery(pOwnerName, //Pointer to OwnerName.
DNS_TYPE_A, //Type of the record to be queried.
DNS_QUERY_STANDARD, // Bypasses the resolver cache on the lookup.
NULL, //Contains DNS server IP address.
&pDnsRecord, //Resource record that contains the response.
NULL); //Reserved for future use. // printf("The host name is %s \n",(pDnsRecord->Data.PTR.pNameHost));
while(pDnsRecord){
printf("The host name is %s \n",pDnsRecord->pName);
printf("the type is %d \n",pDnsRecord->wType);
printf("the lenght of data is %d \n", pDnsRecord->wDataLength);
printf(" the time to live is %d \n", pDnsRecord-> dwTtl);
printf("the lenght of data id %d \n", pDnsRecord-> dwReserved); pDnsRecord=pDnsRecord->pNext;
} printf("dnsCache print over");
}
else
{
printf("ilegal code"); } } void DoFlushDns(bool){ printf("relizing config/flushdns!"); }

转载自:http://blog.csdn.net/dlutbrucezhang/article/details/8577712

ipconfig的C语言实现的更多相关文章

  1. Linux下ipconfig分析及C语言实现

    在linux下使用ifconfigl命令能很方便的查看网卡与网线是否连通,运行ifconfig eth0命令大致输出如下: # ifconfig eth0 eth0 Link encap:Ethern ...

  2. C语言使用cmd命令并获取输出方法

    转自http://blog.csdn.net/hxh129/article/details/8000205 C语言使用cmd命令并获取输出方法 在实践中,我们有时候需要用C语言来调用cmd的命令,并得 ...

  3. C/C++学习----使用C语言代替cmd命令、cmd命令大全

    [开发环境] 物理机版本:Win 7 旗舰版(64位) IDE版本:Visual Studio 2013简体中文旗舰版(cn_visual_studio_ultimate_2013_with_upda ...

  4. C语言运算符与表达式

    1 概论 计算机内存中的数据可以通过变量,常量来表示和存储,那么这些数据如何运算? C语言中提供了大量(34种)的运算符可以用来完成数据的算术,赋值,逻辑,关系,条件判断以及自增自减运算和基于二进制的 ...

  5. c语言基础学习02_windows系统下的cmd命令

    =============================================================================注意:cmd的命令很多,需要用的时候可以查询即 ...

  6. C语言实现ifconfig获取网卡接收和发送流量统计

    在Windows下我们可以利用ipconfig命令获取网卡的相关信息,在Linux下命令是ifconfig 我们可以获取的信息更为丰富,其中包括网卡接收和发送的流量,用C语言实现这个命令并不是一件简单 ...

  7. GO语言的进阶之路-面向过程式编程

    GO语言的进阶之路-面向过程式编程 作者:尹正杰 版权声明:原创作品,谢绝转载!否则将追究法律责任. 我们在用Golang写一个小程序的时候,未免会在多个地方调用同一块代码,这个时候如何优化你的代码呢 ...

  8. D08——C语言基础学PYTHON

    C语言基础学习PYTHON——基础学习D08 20180829内容纲要: socket网络编程 1  socket基础概念 2  socketserver 3  socket实现简单的SSH服务器端和 ...

  9. D05——C语言基础学PYTHON

    C语言基础学习PYTHON——基础学习D05 20180815内容纲要: 1 模块 2 包 3 import的本质 4 内置模块详解 (1)time&datetime (2)datetime ...

随机推荐

  1. 【机房系统知识小结】微软自带RDLC报表,数据汇总设计

    在做机房系统报表的时候,借鉴 八期崔成龙学长的博客< VB.NET rdlc 报表的使用>,照虎画猫的敲了一遍,但是在“汇总项”中,出现了一点小问题. 具体的设计方法在这里就不做介绍了,请 ...

  2. 规则引擎QLExpress的简单应用

    QLExpress 是一个轻量级的类java语法规则引擎,作为一个嵌入式规则引擎在业务系统中使用.让业务规则定义简便而不失灵活.让业务人员就可以定义业务规则.支持标 准的JAVA语法,还可以支持自定义 ...

  3. XtraReport交叉表隐藏列标题及自定义排序

    1.隐藏列标题 用DevExpress PivotGrid report 做报表的时候,将字段拖放到报表中后,ColumnArea和DataArea会显示两个标题字段,如下图: 选中交叉表,设置以下属 ...

  4. [RxJS] Filtering operators: takeUntil, takeWhile

    take(), takeLast(), first(), last(), those opreators all take number or no param. takeUtil and takeW ...

  5. 通过MultipleOutputs写到多个文件

    MultipleOutputs 类可以将数据写到多个文件,这些文件的名称源于输出的键和值或者任意字符串.这允许每个 reducer(或者只有 map 作业的 mapper)创建多个文件. 采用name ...

  6. tcmalloc源码剖析的资料

    1. https://seanhn.wordpress.com/2011/04/14/exploit-necromancy-in-tcmalloc-reviving-the-4-to-n-byte-o ...

  7. Linux shell用法和技巧

         使用Linux shell是我每天的基本工作,但我经常会忘记一些有用的shell命令和l技巧.当然,命令我能记住,但我不敢说能记得如何用它执行某个特定任务.于是,我开始在一个文本文件里记录这 ...

  8. HTTP协议基础与实验

    一. HTTP协议(Hypetext Transfer Protoacal,超文本传输协议) HTTP协议规定了Web基本的运作过程,以及Web服务器之间的通信细节. Http协议采用客户端/服务器端 ...

  9. cocos2dx 各种环境的搭建

    http://www.cocos.com/doc/tutorial/index?type=cocos2d-x Windows7上搭建Cocos2d-x 3.4开发环境 这里需要注意的是,如果是搭建VS ...

  10. 脚本动态监控input

    Jquery $('input').bind('input propertychange', function() { //进行相关操作 }); JS if(isIE) { document.getE ...