AD

java network access outside the local LAN IP

Recently, the house to meet two Azeri communications needs, need to be outside the local network IP to tell the people to another room. Years ago are calling a group, I am here, IP is XXXX, that one day their own whim, to achieve this through the program to automate the process of notification. So the demand set for ourselves.

Requirements: basic target to boot to the local IP routing WAN port to inform the other party.

Thinking: If it can be automatically notified?

First, there must be a public space, can be used as a carrier notification.

Second, the need to issue the notice to the transport mechanism.

On reflection, I think the e-mail, mail is everyone's, email can be issued with a degree. So the demand has become a way through the mail the latest issue to get to the IP. Jiejue ideas have, the biggest problem is how to obtain the external network IP, started trying to obtain local IP, this is obviously useless, because the machine is included in net Huan Jing, Dao's but rather an access network IP, then Shitu want to get external network IP, such as visit a XXX site to obtain the form of IP, this kind of site really a lot, but are available to the public network IP, the network learned people know the public IP network of small, often only in the network node on the IP, this IP on my ADSL users, almost no one of any significance. In fact, I just need to route the WAN port IP. Internet search, I did not find suitable. In almost desperate, I think of a proxy, I can not access router way to get the IP then, I tried to use telnet login routing, attempt to manipulate routing routing commands, results, and I imagine the same route home after all Bushi server-level routing, not to provide access to the external command, can only be achieved by way of web-routing settings. Themselves once again into despair, then I open the fireBug, trying to find that view IP IP jump page. The results were I found, **192.168.1.1/userRpm/StatusRpm.htm, point response to open the page view, mass is part of a page over information. OK, this is what I want to IP. I suddenly excited, but this was not enough, because every time when landing routes enter a user name and password. Internet search found that this is not difficult, agent service program as written on. After a night of reflection and practice considered to be WAN port IP I am out out.

package com.eehome.app.mail.utils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java**.Authenticator;
import java**.URL;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.eehome.app.mail.IMailConstant;
import com.eehome.app.mail.model.RouterPassAuth;

/**
 * @author wensong
 * 2010-9-4   PM 03:34:58
 */
public class RouteIpUtils {

        private final static RouteIpUtils routeIpUtils = new RouteIpUtils();
        
        
        private RouteIpUtils() {

        }

        public static RouteIpUtils getInstance() {
                //  Validation tool to register an instance of  
                Authenticator.setDefault(new RouterPassAuth());
                return routeIpUtils;
        }

        public String getRouteIp() throws IOException {
                StringBuffer wanPacket = getWanPacket();
                return getFirstIp(wanPacket);
        }

        /**
         *   Access routes in the state of Web page data  
         * 
         * @return
         * @throws IOException
         */
        private StringBuffer getWanPacket() throws IOException {
                URL url = new URL(IMailConstant.ROUTE_WEB_STATE);
                InputStream ins = null;
                try {
                        ins = url.openConnection().getInputStream();
                        BufferedReader reader = new BufferedReader(new InputStreamReader(ins));
                        String str;
                        boolean flag = false;
                        StringBuffer wanPacket = new StringBuffer();
                        int num = 3;
                        while ((str = reader.readLine()) != null && num > 0) {
                                if (str.contains("var wanPara = new Array(")) {
                                        flag = true;
                                }
                                if (flag) {
                                        wanPacket.append(str);
                                        num--;
                                }
                        }
                        return wanPacket;
                }finally{
                        if(ins!=null){
                                ins.close();
                        }
                }
        }

        private String getFirstIp(StringBuffer wanPacket) {
                //   Identify the data packet matches the first IP, is the  Ip
                Pattern p = Pattern**pile("\\d+\\.\\d+\\.\\d+\\.\\d+");
                Matcher m = p.matcher(wanPacket);
                if (m.find()) {
                        return m.group();
                } else {
                        return null;
                }
        }
        
        public static void main(String[] args) {
                try {
                        System.out.println(RouteIpUtils.getInstance().getRouteIp());
                } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                }
        }
}
package com.eehome.app.mail;

public interface IMailConstant {

        /**
         *   Sender address  
         */
        public final static String NOTIFY_EMAIL_MESSAGE_FROM = "[email protected]**";

        /**
         *   Reminder message headers prefix  
         */
        public final static String NOTIFY_EMAIL_MESSAGE_PRE_TITLE = "  Notice  :  Server IP reminded  ----";

        /**
         *   Routing User Name  
         */
        public final static String ROUTE_USER = "admin";

        /**
         *   Routing code  
         */
        public final static String ROUTE_PWD = "huang";

        /**
         *   Web page records the state of the routing  ,  Which contains the Wan port  ip
         */
        public final static String ROUTE_WEB_STATE = "**192.168.1.1:83/userRpm/StatusRpm.htm?Connect=  Connection  &wan=1";

        /**
         *   Polling hours 10 minutes  
         */
        public final static long POLLING_TIME = 10 * 60 * 1000;

        /**
         * email  File address  
         */
        public final static String EMAIL_FILE_PATH = "/root/mail/mail.txt";

        /**
         * log4j  Store address  
         */
        public final static String LOG4J_FILE_PATH = "/root/mail/log/log4j.properties";

        /**
         *   Matching regular email  
         */
        public final static String EMAIL_REG = "[A-Za-z0-9](?:[0-9a-zA-Z_]?\\.?){4,24}@[0-9a-zA-Z_-]{1,59}\\.(?:[0-9a-zA-Z]\\.?[0-9a-zA-Z]?){2,3}";
}
package com.eehome.app.mail.model;

import java**.Authenticator;
import java**.PasswordAuthentication;

import com.eehome.app.mail.IMailConstant;


public class RouterPassAuth extends Authenticator {
        
        @Override
        public PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(IMailConstant.ROUTE_USER,
                                IMailConstant.ROUTE_PWD.toCharArray());
        }

}

Considering IP routing is dynamic IP, over a period of time will change to the program I designed a polling mechanism to detect IP, changes to schedule jobs with regular Get IP, compare, and then decide whether to send the message.

package com.eehome.app.mail.task;

import java.io.IOException;
import java.util.Arrays;

import org.apache**mons.logging.Log;
import org.apache**mons.logging.LogFactory;
import org.apache.log4j.PropertyConfigurator;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.mail.javamail.JavaMailSender;

import com.eehome.app.mail.IMailConstant;
import com.eehome.app.mail.model.IpNotifyMessage;
import com.eehome.app.mail.utils.RouteIpUtils;

/**
 *   E-mail alert mission  
 * @author wensong
 * 2010-9-5   PM 11:12:17
 */
public class NotifyEmailSendTask implements Runnable {

        private String[] toMails;
        private Log logger = LogFactory.getLog(this.getClass());

        private static String ip = "192.168.1.110";

        static {
                PropertyConfigurator.configure(IMailConstant.LOG4J_FILE_PATH);
        }

        private static BeanFactory factory = new ClassPathXmlApplicationContext(
                        "application-context.xml");

        public NotifyEmailSendTask(String[] toMails) {
                this.toMails = toMails;
        }

        public void run() {
                String routerIp = null;
                try {
                        routerIp = RouteIpUtils.getInstance().getRouteIp();
                } catch (IOException e1) {
                        logger.warn("  Connection routing interrupt, or routing connection exception  :" + e1);
                }
                try {
                        if (routerIp != null&&!routerIp.equals("0.0.0.0")) {
                                if (!routerIp.equals(ip)) {
                                        if (!ip.equals("192.168.1.110"))
                                                logger**("  IP routing changes  ,  Send Mail task execution  ");
                                        StringBuffer context = new StringBuffer().append(
                                                        "  Today  Host:\n").append("eehome**  ")
                                                        .append(routerIp);
                                        if (!ip.equals("192.168.1.110")) {
                                                context = new StringBuffer().append("Host  Changes are as follows  :\n")
                                                                .append("eehome**  ").append(routerIp);
                                        }

                                        //   E-mail message object constructor  
                                        IpNotifyMessage message = new IpNotifyMessage(toMails,
                                                        context.toString());
                                        //   Email  
                                        JavaMailSender mailSender = (JavaMailSender) factory
                                                        .getBean("javaMailSender");
                                        logger**("  Send e-mail, send mail to  :" + Arrays.toString(toMails));

                                        mailSender.send(message);
                                        ip = routerIp;
                                } else {
                                        logger.debug("  IP is the last record  :" + ip + ",   New IP-routing  :" + routerIp
                                                        + "   Poll results will not send e-mail  ");
                                }
                        }
                } catch (Exception e) {
                        logger.warn("  Send exception e-mail  :" + e);
                }

        }

}
package com.eehome.app.mail.task;

import java.util.concurrent.TimeUnit;

import com.eehome.app.mail.IMailConstant;
import com.eehome.app.mail.utils.EmailsProvider;
import com.eehome.core.task.EeHomeScheduledExecutor;

/**
 *  E-mail task scheduling, the use of polling way to check the routing  IP  Is changed, if you change email  
 * 
 * @author wensong 2010-9-4   PM 03:34:58
 */
public class IpNotifyEmailSchedule {

        public static void main(String[] args) {
                String[] mails = EmailsProvider.getInstance().getEmailArrays();
                EeHomeScheduledExecutor.getScheduledExecutor().scheduleWithFixedDelay(
                                new NotifyEmailSendTask(mails), 0, IMailConstant.POLLING_TIME,
                                TimeUnit.MILLISECONDS);
        }
}


package com.eehome.app.mail.model;

import java.util.Date;

import org.springframework.mail.SimpleMailMessage;

import com.eehome.app.mail.IMailConstant;
import com.eehome.app.mail.utils.DateUtils;

public class IpNotifyMessage extends SimpleMailMessage {

        private static final long serialVersionUID = -3236307360187426650L;

        public IpNotifyMessage(String toMail, String toText) {
                //   Set the message header  :  Reminder message headers prefix + current time  
                setSubject(IMailConstant.NOTIFY_EMAIL_MESSAGE_PRE_TITLE
                                + DateUtils.getTimeNow());
                setFrom(IMailConstant.NOTIFY_EMAIL_MESSAGE_FROM);
                setSentDate(new Date());
                setTo(toMail);
                setText(toText);
        }
        
        public IpNotifyMessage(String[] toMails,String toText){
                //   Set the message header  :  Reminder message headers prefix + current time  
                setSubject(IMailConstant.NOTIFY_EMAIL_MESSAGE_PRE_TITLE
                                + DateUtils.getTimeNow());
                setFrom(IMailConstant.NOTIFY_EMAIL_MESSAGE_FROM);
                setSentDate(new Date());
                setTo(toMails);
                setText(toText);
        }
}


package com.eehome.app.mail.exception;

public class FileIsNotExistException extends Exception {

        /**
         *   File does not exist exception  
         */
        private static final long serialVersionUID = -2545287258814097123L;

        public FileIsNotExistException() {
                super();
        }

        public FileIsNotExistException(String message, Throwable cause) {
                super(message, cause);
        }

        public FileIsNotExistException(String message) {
                super(message);
        }

        public FileIsNotExistException(Throwable cause) {
                super(cause);
        }

}
package com.eehome.app.mail.utils;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache**mons.logging.Log;
import org.apache**mons.logging.LogFactory;
import org.apache.log4j.PropertyConfigurator;

import com.eehome.app.mail.IMailConstant;

public class EmailsProvider {

        private final static EmailsProvider provider = new EmailsProvider();
        private Log logger = LogFactory.getLog(this.getClass());

        static {
                PropertyConfigurator.configure(IMailConstant.LOG4J_FILE_PATH);
        }

        private EmailsProvider() {

        }

        public static EmailsProvider getInstance() {
                return provider;
        }

        /**
         *   Email array access  
         * 
         * @return
         */
        public String[] getEmailArrays() {
                StringBuilder sb = getEmailStrBuilder();
                if (sb != null) {
                        List<String> mailArrays = getEmails(sb);
                        return (String[]) mailArrays.toArray(new String[mailArrays.size()]);
                } else {
                        return null;
                }
        }

        /**
         *   Get the configuration from the specified email  email
         * 
         * @return
         */
        private StringBuilder getEmailStrBuilder() {
                File file = new File(IMailConstant.EMAIL_FILE_PATH);
                InputStream ins = null;
                StringBuilder stringBuilder = new StringBuilder();
                try {
                        ins = new FileInputStream(file);
                        BufferedReader reader = new BufferedReader(new InputStreamReader(
                                        ins));
                        String str;
                        while ((str = reader.readLine()) != null) {
                                stringBuilder.append(str).append(",");
                        }
                        return stringBuilder;
                } catch (FileNotFoundException e) {
                        logger**(file.getPath() + "  File does not exist  ");
                        return null;
                } catch (IOException e) {
                        logger**("  File operation exceptions  :" + e);
                        return null;
                } finally {
                        try {
                                ins.close();
                        } catch (IOException e) {
                                logger**("  File closed Exception  :" + e);
                                return null;
                        }
                }

        }

        /**
         *   Matched by the regular characters  
         * @param stringBuilder
         * @return
         */
        private List<String> getEmails(StringBuilder stringBuilder) {
                List<String> mails = new ArrayList<String>();

                //   Create a regular expression  
                Pattern p = Pattern**pile(IMailConstant.EMAIL_REG);
                Matcher m = p.matcher(stringBuilder);

                if (logger.isDebugEnabled()) {
                        logger.debug("  File read string  stringBuilder:" + stringBuilder);
                }

                //   The string match is found  
                while (m.find()) {
                        mails.add(m.group());
                }
                return mails;
        }

}
package com.eehome.app.mail.utils;

import java.text.SimpleDateFormat;
import java.util.Date;

public class DateUtils {

        public static final SimpleDateFormat sdf = new SimpleDateFormat(
                        "yyyyMMddHHmmss");

        /**
         *   Get the current time string of the format  yyyyMMddHHmmss
         * @return
         */
        public static String getTimeNow() {
                return sdf.format(new Date());
        }
}


package com.eehome.app.mail.exception;

public class FileIsNotExistException extends Exception {

        /**
         *   File does not exist exception  
         */
        private static final long serialVersionUID = -2545287258814097123L;

        public FileIsNotExistException() {
                super();
        }

        public FileIsNotExistException(String message, Throwable cause) {
                super(message, cause);
        }

        public FileIsNotExistException(String message) {
                super(message);
        }

        public FileIsNotExistException(Throwable cause) {
                super(cause);
        }

}


Then in order to write a shell script to implement it as a background script, put rc.local, the allowed boot, so the message to remind the procedure done on IP, Oh.
标签: e mail, access network, mail mail, jump page, network node, local ip, port ip, local network, server level, java network, wan port, public space, huan jing, transport mechanism, routing commands, adsl users, xxx site
分类: Java
时间: 2010-09-13

相关文章

  1. simple java program thread scan LAN ip

    import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.I ...
  2. Java Network Programming "shorthand"

    1. What is the TCP / IP protocols? 2. TCP / IP transport protocol which of two kinds, each What are the charac ...
  3. Java network programming sperm solution (01)

    1 OSI Reference Model 1.1 ISO International Organization for Standardization (International Organization for S ...
  4. Java Network Programming (11): get network interface to use the letter NetworkInterface class

    Starting from JDK1.4, Java provides a NetworkInterface class. This class can get the machine all of the physic ...
  5. The jdom appears strange network access

    Struts2 with jdom parsing a configuration file of the code, the recent exception of the inexplicably cast. Loo ...
  6. Flex solutions for access to the local DLL

    Recent projects do need to use Flex to create a desktop application, but do not use Flex AIR, because of the n ...
  7. linux small note - LAN + IP settings

    netmask ip address subnet mask broadcast gateway gateway dns DNS server vmware three internet access settings: ...
  8. java network programming instructions

    java network programming refers to the network transport layer is based on Socket programming. Network communi ...
  9. JAVA to access firebird database of Jaybird

    JAVA to access firebird database of Jaybird About Jaybird-2.1.6JDK_1.5 used as follows: First: Install Jaybird ...
  10. Java Network Launching Protocol

    Early in the java development, with emphasis being placed on client development. Language to download the appl ...
  11. JAVA connection ACCESS, SQL Server, MySQL, Oracle Database

    import java.sql .*; / * * JAVA connection ACCESS, SQL Server, MySQL, Oracle Database * * * / public class JDBC ...
  12. Sql * Plus network access basic principles and resolve related terms

    sql * plus network access to run the basic mechanism: listener.ora file SID_LIST_LISTENER = # naming SID_LIST_ ...
  13. java使用JNA(Java Native Access)调用dll的方法

    java使用JNA(Java Native Access)调用windows系统的dll文件的例子 JNA(Java Native Access):建立在JNI之上的Java开源框架,SUN主导开发,用来调用C.C++代 ...
  14. Linux, public network access to local / external network IP

    Run the command: curl http://members.3322.org/dyndns/getip
  15. java network programming under the domain name for ip address, URL

    Domain Name, the domain can be converted to ip address InetAddress can also use the getAddress () to get the I ...
  16. vm ubuntu10 IP configuration, network access to hosts

    Phenomenon Vm After installation, the default is NAT mode. After installation, configure the dns, Internet ok. ...
  17. Tomcat services in the local area network access settings

    In the tomcat service in the LAN can access the following three kinds of settings: 1) http://localhost/webName ...
  18. Using the external network to access the svn server LAN

    svn server using VisualSVN-Server, the system using a windows2003, Conditions: Svn in the LAN has set up, each ...
  19. LAN to external network access to my tomcat

    First: Open a browser, enter the router IP, default is 192.168.1.1; Second: Check the public network IP ; Thir ...