一时兴起写的C++定期监测服务器IP变动并发送邮件的小工具

动机

由于实验室Windows服务器经常由于各种原因导致IP变动,所以就想在IP变动后自动获取新的IP并发邮件告诉我。

PS.由于我们实验室的服务器的校园网只需要连接上就能上网,而且是动态IP,所以就没有在这里写网络登录,或者去网络中心申请固定IP(自己申请太麻烦了,嘿嘿)。
​
PPS.文章原创,欢迎转载,转载请注明出处。文中贴出了所有代码,想支持下作者可以去对应CSDN下载支持。
PPPS.感谢作者写作过程中参考的文章和资料作者。
​
最新更新时间:2019/10/10 22:00 by seu_wangpeng

准备

根据经验,这里主要就分三步走了

  1. 获取本地IP,判断IP是否变化。

  2. 实现发邮件功能。

  3. 设置服务器计划任务,在开机,或者定时运行检查。

东西比较简单,就想用最简单的方式,最快完成就好了。

获取IP

Windows获取IP好像平时用的最多的就是直接cmd敲出来,用ipconfig指令咯,就像这样

一般找到 以太网适配器 下面的 IPv4就是我们要的了。

然后C/C++程序里获取这个保存为文件可以使用重定向符 >system() 就可以保存查询的结果到ipInfo.txt文件了。

system("ipconfig >ipInfo.txt")

整理数据

获取到的IP数据信息有时候就有点多,而我只想关注以太网IP,或者无线网IP等信息,注意到这里的输出信息是一节一节输出的,而且每一节有一个标题,标题每行置顶,而每节内部要么是空行,要么是有空格开头。根据这些特点,这里我就写了一个处理数据的类,算是一点美化(我不会说这是强迫症)。

代码也贴出来,东西不多就不注释了:

/*
*   readconfig.hpp --- read result of "ipconfig"
*   @How to : using system("ipconfig >ipInfo.txt") to get ip info file first.
*   @author : wangpeng(seu_wangpeng@qq.com)
*   @version : v1.0 2019/10/10
*/
​
#pragma once
​
#include <string>
#include <iostream>
#include <fstream>
#include <sstream>
#include <vector>
​
using namespace std;
​
class ReadConfig
{
    struct Section
    {
        string header;
        vector<string> contents;
    };
    
public:
    ReadConfig(std::string path)
    {
        std::ifstream fin(path.c_str());
        string line;
        bool secFlag=false;
        Section section;
        while(getline(fin,line))
        {
            if(line[0]!=' ' && line[0]!='\t' && line!="")
            {
                if(secFlag)
                {
                    sections.push_back(section);
                }
                secFlag=true;
                section.header=line;
                section.contents.clear();
                section.contents.push_back(line);
            }
            else
            {
                if(secFlag)
                {
                    section.contents.push_back(line);
                }
            }
            content+=(line+"\n");       
        }
        sections.push_back(section);
​
        fin.close();
    }
    
    ~ReadConfig()
    {
    }
    
    std::string getSection(std::string sec)
    {
        std::string result="";
        for(int i=0;i<sections.size();i++)
        {
            if(sections[i].header.find(sec)!=std::string::npos)
            {
                for(int j=0;j<sections[i].contents.size();j++)
                {
                    result += (sections[i].contents[j]+"\n");
                }
            }
        }
        return result;
    } 
    
    std::string getContent()
    {
        return content;
    }
    
private:
    std::string content;
    vector<Section> sections;
​
};
  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值