本文主要是介绍监听IP地址,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
本例实现从文件中读取IP地址并存储在结点链表中,每一个结点存储IP地址数据,并统计该IP地址在数据文件中出现的次数。随着每一个地址的读取,检查是否已经在链表中了。如果在,就将计数器加1,否则简单地将其插入链表尾部。
/***********************************************
Input (keyboard):name of file containing IP addresses(file):address
Output:a list of distinct addresses and their counts
************************************************/#include <iostream>
#include <cassert>
#include <string>
#include <iomanip>
#include <fstream>
#include <algorithm>
#include <list>using namespace std;class AddressCounter{
private:string address;int count;
public:void read(istream& in){in>>address;count=1;}void print(ostream& out)const{out<<setw(15)<<left<<address<<" occurs "<<count<<" times"<<endl;}void tally(){count++;}bool operator==(const AddressCounter& addr2){return address==addr2.address;}string getAddress()const{return address;}
};
typedef list<AddressCounter> IP_List;int main()
{string fileName;IP_List addrCountList;ifstream inStream;cout<<"Enter name of file containing IP addresses:";cin>>fileName;inStream.open(fileName.data());assert(inStream.is_open());AddressCounter item;for(;;){item.read(inStream);if(inStream.eof())break;IP_List::iterator it=find(addrCountList.begin(),addrCountList.end(),item);if(it!=addrCountList.end())(*it).tally();elseaddrCountList.push_back(item);}cout<<endl<<"Address and Counts:"<<endl;for(IP_List::iterator it=addrCountList.begin();it!=addrCountList.end();it++)(*it).print(cout);return 0;
}
执行效果如下图:
这篇关于监听IP地址的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!