设备公网IP变更提醒

        我们开通宽带,会用自己本地设备进行一些服务,奈何,电信的公网IP会隔段时间就变动。我们身处异地,有时可能无法知晓更新的IP,甚至,不知道IP已经变动,这时就需要写一个服务,监听公网IP变动,并进行通知。

        我是这样完成的,宝塔计划任务每分钟访问我们的PHP脚本,我们的脚本,获取IP并与之前的IP对比,不一样则更新并通知,通知我是用的宝塔邮局发送邮件,关于宝塔邮局发送邮件之前有帖子介绍:

        PHP脚本我是这样写的:

<?php
function curlget($url,$method='get',$data=null){
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 1000);
curl_setopt($ch, CURLOPT_TIMEOUT, 500);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
if($method=='post'){
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch,CURLOPT_POSTFIELDS,$data);
}
$result = curl_exec($ch);
curl_close($ch);
if(!$result){
//curl 出现错误
return false;
}
return $result;
}
//发送邮件 宝塔邮件系统发送
function send_mail($email,$subject,$content){
 
        $postdata = [
            'mail_from' => '宝塔邮局邮箱', //kekc@kekc.cn
            'password' => '宝塔邮局密码',
            'mail_to' => $email,
            'subject' => $subject,
            'content' => $content,
        ];
        $url = 'http://宝塔邮局的IP:8888/mail_sys/send_mail_http.json';
        $res = @curlget($url,"post",$postdata);
        $res = json_decode($res,true);
        if($res['status']){
            return true;
        }else{
            return false;
        }
 
}
function get_client_ipss() {
return keep_str(get_real_ips(), '0123456789ABCDEFabcdef:.');
}
function keep_str($str, $keep = '0123456789ABCDEFabcdef:.') {
$out = '';
$len = strlen($str);
for ($i = 0; $i < $len; $i++) {
$s = $str[$i];
if (strpos($keep, $s) === false) {
continue;
}
$out .= $s;
}
return $out;
}
function get_real_ips() {
if (!empty($_SERVER['HTTP_X_REAL_IP'])) {
return $_SERVER['HTTP_X_REAL_IP'];
}
if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
return $_SERVER['HTTP_CLIENT_IP'];
}
if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
$arr = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
$pos = array_search('unknown', $arr);
if (false !== $pos) unset($arr[$pos]);
return trim($arr[0]);
}
return $_SERVER['REMOTE_ADDR'];
}
$act = $_REQUEST['act'];
$file = "/www/wwwroot/www.kekc.cn/public/ip.txt";//这里记得事先新建文件,并修改为自己的目录
if($act == "updateip"){//玩客云访问
    $ip=get_client_ipss();//获取访问者IP
    if($ip!=file_get_contents($file)){//IP发生改变
        file_put_contents($file, $ip);
        $sendemail = send_mail("通知到的邮箱","玩客云IP更新提醒","玩客云IP已经更新为:".$ip);//此处为通知,你也可以自己写自己的通知
        if($sendemail){
            echo "IP更新完成,邮件发送成功!";
        }else{
            echo "IP更新完成,邮件发送失败!";
        }
        exit;
    }else{
        echo "IP不变化!";
        exit;
    }
}else{//普通访问
    echo '玩客云IP:'.file_get_contents($file);
}
© 版权声明
THE END
喜欢就支持一下吧
点赞6 分享