[原创]drcom客户端ip自动更新程序

上网、浏览、聊天、下载等
回复
lishen2
帖子: 5
注册时间: 2007-05-31 17:53

[原创]drcom客户端ip自动更新程序

#1

帖子 lishen2 » 2007-06-26 13:31

本人所在学校上网使用drcom客户端,DHCP动态分配地址。从论坛上下载一个drcom的客户端,每次上网都得手动更改/etc/drcom.conf文件中的IP地址。很是麻烦我用KDEVELOP写了一个小程序,自动更改drcom.conf中的IP地址。上传上来大家分享一下,编译好的程序在附件里。可以再些一个bash脚本,每次运行就可以自动上网。欢迎提意见。

代码: 全选

#ifdef HAVE_CONFIG_H
#include <config.h>
#endif

#include <fstream>
#include <string>
#include <iostream>
#include <cstdlib>
using namespace std;

bool openfile(string filename,string &Str)
{
	ifstream infile(filename.c_str());
	if(!infile)
	{
		cerr<<"Error:unable to open file '"<<filename<<"'"<<endl;
		return false;
	}
	string temp;
	while(infile>>temp)
	{
		Str+=temp;
		Str+='\n';
	}
	infile.close();
	return true;
}

string findip(string contents,const string &inString)
{
	string::size_type pos=inString.find(contents.c_str());
	if (pos>inString.size())
	{
		cerr<<"No '"<<contents<<"' in the file this file."<<endl;
		exit(-1);
	}
	while(inString[pos]!=':') ++pos;
	++pos;
	string ip;
	while(inString[pos]!='\n')
	{
		ip+=inString[pos];
		++pos;
	}
	return ip;
}

void replace(string &originally,string source,string target)
{
	string::size_type start=originally.find(source.c_str()),end=0;
	while(originally[start]!='=')
	{
		++start;
	}
	++start;
	end=start;
	while(originally[end]!='\n') ++end;
//	string::iterator tmp;
	originally.erase(start,end-start);
	originally.insert(start,target);

}

void writefile(string filename,string &contants)
{
	ofstream outfile(filename.c_str());
	outfile<<contants<<endl;
	outfile.close();
}

int main(int argc, char *argv[])
{
	string ipfile,ip,drcom;

	system("ifconfig> /tmp/temp_ip");
	if(!openfile("/tmp/temp_ip",ipfile)) return -1;
	ip=findip("地址:",ipfile);
	system("rm /tmp/temp_ip");

	if(!openfile("/etc/drcom.conf",drcom)) return -1;
	replace(drcom,"nic0=",ip);
	writefile("/etc/drcom.conf",drcom);
	cout<<"IP update successful."<<endl;

  return EXIT_SUCCESS;
}
附件
update_ip.tar.gz
(7.87 KiB) 已下载 48 次
回复