java小程序自动报告内网服务器的公网IP地址
公司搭了一SVN服务器,由于没有固定IP地址。在公司记下IP往邮件一发,回家想通过这个IP连上服务器,发现在IP不对。所以想一办法,写一小程序,让服务器自动检测外网IP地址发到邮箱。这样就可以回家取下邮件拿到IP,就可连上SVN服务器(注已做好端口映射)。说下原理:
1.用URL连上一可查看IP地址的网址,取下当前服务器的公网IP地址
2.进行下判断,看拿到的IP地址,是否有变,没变不处理,有变发邮件
3.将取得的公网IP地址发指定邮箱
4.使用定时器,定时执行2步骤
5.通过IDE(本人采用Eclipse)生成可执行jar
话不多说上代码:
package com.huzy.autoip;import java.io.BufferedInputStream;import java.io.BufferedReader;import java.io.IOException;import java.io.InputStreamReader;import java.net.MalformedURLException;import java.net.URL;import java.util.Date;import java.util.Properties;import java.util.Timer;import java.util.TimerTask;import java.util.regex.Matcher;import java.util.regex.Pattern;import javax.mail.Authenticator;import javax.mail.Message;import javax.mail.PasswordAuthentication;import javax.mail.Session;import javax.mail.Transport;import javax.mail.internet.InternetAddress;import javax.mail.internet.MimeMessage;public class AutoIP {private static String localIP = "127.0.0.1";public static void main(String[] args) throws Exception {timer();}private static String getLocalIp() {URL url = null;try {url = new URL("http://www.ip138.com/ip2city.asp");} catch (MalformedURLException e) {e.printStackTrace();}BufferedInputStream bis;try {bis = new BufferedInputStream(url.openStream());InputStreamReader isr = new InputStreamReader(bis);BufferedReader reader = new BufferedReader(isr);String s = null;while ((s = reader.readLine()) != null) {if (s.trim().equals(""))continue;String regEx = "(25|2|{1}{2}|{1}{1}|)\\.(25|2|{1}{2}|{1}{1}||0)\\.(25|2|{1}{2}|{1}{1}||0)\\.(25|2|{1}{2}|{1}{1}|)";Pattern pat = Pattern.compile(regEx);Matcher mat = pat.matcher(s);boolean rs = mat.find();if (rs)return mat.group(0);}bis.close();} catch (IOException e) {e.printStackTrace();}return null;}public static void sendMail(String content) throws Exception {Properties props = System.getProperties();props.setProperty("mail.smtp.auth", "true");props.setProperty("mail.host", "smtp.163.com");Session session = Session.getInstance(props, new Authenticator() {@Overrideprotected PasswordAuthentication getPasswordAuthentication() {return new PasswordAuthentication("your_name@163.com", "your_password");}});Message message = new MimeMessage(session);message.setSubject("hello");message.setRecipients(Message.RecipientType.TO, InternetAddress.parse("one@163.com"));message.setFrom(new InternetAddress("your_name@163.com"));message.setText("the time " + new Date() + " IP " + content);Transport.send(message);}public static void timer(){ Timer timer = new Timer(); timer.schedule(new MyTask(), 0, 10 * 1000); }public static class MyTask extends TimerTask {private String newIP = null;@Overridepublic void run() {try {newIP = getLocalIp();if(newIP != null) {if (!newIP.equals(localIP)) {localIP = newIP;sendMail(localIP);}}} catch (Exception e) {e.printStackTrace();}}}}
页:
[1]