C++输出IP地址段内的合法地址

近半年的Intel实习生活快要结束了.马上要找工作了,这段时间打算把以前的知识复习复习,顺便在这里记录一下.这是当时去Intel面试的时候,面试官问的一道题.当时因为时间关系,只让我提供一个思路,并没有写出具体实现过程.下面把实现过程写上.主要是把IP地址转换成整数,这样比截取IP地址每一段内的值出来要快.最后把所有合法IP地址输出到文件中.

#include <iostream>
#include <string>
#include <WinSock.h>
#include <fstream>
#pragma comment(lib,"ws2_32.lib")
using namespace std; int main()
{
string startIPAddr, endIPAddr;
unsigned long startIP, endIP, index;
cout<<"input start and end IP"<<endl;
cin>>startIPAddr>>endIPAddr;
startIP = htonl(inet_addr(startIPAddr.c_str()));
endIP = htonl(inet_addr(endIPAddr.c_str()));
if(startIP > endIP)
{
cout<<"startIP must be smaller than endIP"<<endl;
return 1;
}
else
{
struct in_addr addr;
ofstream outfile("IPAddr.txt",ios::ate);
for(index = startIP; index <= endIP; index++)
{
addr.S_un.S_addr = ntohl(index);
outfile<<inet_ntoa(addr)<<"\n";
}
outfile.close();
}
getchar();
return 0 ;
}

以上使用的是Socket头文件中自带的对IP地址操作的函数,下面可以自己编写IP地址转换成长整型以及长整型转换成IP地址的函数.

unsigned long iptol(const string& strip)
{
int a[4];
string ip = strip;
string strtemp;
size_t pos;
size_t i=3; do
{
pos = ip.find("."); //以点将IP地址分成四段,对每段的数字进行转换
if(pos != string::npos) //当搜索整个字符串完后,仍没find到要的字符,则返回npos
{
strtemp = ip.substr(0,pos);
a[i] = atoi(strtemp.c_str());
i--;
ip.erase(0,pos+1);
}
else
{
strtemp = ip;
a[i] = atoi(strtemp.c_str());
break;
}
}while(1);
unsigned long lresult = (a[3]<<24) + (a[2]<<16)+ (a[1]<<8) + a[0];
return lresult;
} string ltoip(const unsigned long& nvalue)
{
char strtemp[20];
sprintf( strtemp,"%d.%d.%d.%d",
(nvalue&0xff000000)>>24,
(nvalue&0x00ff0000)>>16,
(nvalue&0x0000ff00)>>8,
(nvalue&0x000000ff) ); return string(strtemp);
}

参考:http://blog.csdn.net/hityct1/article/details/3861205

版权声明:本文为博主原创文章,未经博主允许不得转载。

上一篇:YYModel 源码解读(二)之NSObject+YYModel.h (3)


下一篇:ubuntu 开机显示错误:无法应用原保存的显示器配置