外部IPのWindows通知サービス(External IP Windows Notification Service)


原文:http://www.codeproject.com/Articles/835980/External-IP-Windows-Notification-Service
Introduction
Download External IPChecker.zip
Download ExternalIPChecker-noexe.zip
What is external IP address?An external IP address is the address assigned to you by your Internet Service Provider.IP address is what the other PCs can see from outside your LAN(Local Area Network) 
外部IP的Windows通知服务(External IP Windows Notification Service)_第1张图片
It deepens by the ISP(Internet Service Provider)to set you a static external IP or in most cases mine a dynamic one.       In order to connect to a device inside your network,you will need to redirect the whole traffic(or just the traffic for the remote desk connect or web server-the port you want)the IP address of the device the.Thveris     You can see my setup of my SKY router.This shoud be very easure to configur and is not the main idea of the artic le.
So what happens if the external IP has changed?あなたのcan't access your local pc or device to which you have redirected the traffic,because you do not know the external IP address.have to use.The article gives a solution of solution proble by miplement the Windows
Background
To get notified when the external IP is changed requires aplication that will n all the time,will check the external IP address and if there is a change will send an email notification.For that requement the,Windows bert PCthe y run on the background-so you will not notice any consolip starting and stopping if we chosen a consosolove ap which starts by schedule task alternative for example.
 
Using the code
To get the external IP address I am using a service.When you write in google「What's my IP」you will get a lot of result.You can switch to a different service,but this is what I am using:     http://checkip.dyndns.org/     I am using this code: 

 Collappse
 |  Copyコード
public static string GetExternalIp()
{
    try
    {
       var externalIP = (new WebClient()).DownloadString("http://checkip.dyndns.org/");
             externalIP = (new Regex(@"\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}"))
                                 .Matches(externalIP)[0].ToString();
                    return externalIP;
    }
       catch { return null; }

}
    
Which parses the reponse of the service.     I am caling that service on reglar time intervals-every 30 min.This is a configration in the.config file where the setting is in seconds.     To send an email,I am using my google account to logn into their SMTP server with the SSL enabed feature.Some other SMTP doesn't support that can check and mofy that option.This the code seement

 Collappse
 |  Copyコード
public void SendResetEmail(string ipAddress)
{
   try
    {
           var email = new MailMessage
           {
               From = new MailAddress(ConfigurationManager.AppSettings["EmailAddressFrom"])
           };
    
           email.To.Add(new MailAddress(ConfigurationManager.AppSettings["EmailAddressTo"]));
           email.Subject = "External IP Changed!";
           email.IsBodyHtml = true;
           email.Body = "The IP Address is: " + ipAddress;
           var smtpClient = new SmtpClient
           {
                EnableSsl = true
           };
    
          smtpClient.Send(email);
     }
     catch (Exception ex)
     {
         Program.Logger.Log(ex, LoggerExt.LogExtType.Error);
     }
 }
The service is using a timer,which will fire an event on time intervals and do the check:    

 Collappse
 |  Copyコード
private void OnTimedEvent(object sender, ElapsedEventArgs e)
{
      lock (_locker)
      {
         Program.Logger.Log("Elapsed", LoggerExt.LogExtType.Info);
         var externalIPAddress = IPHelper.GetExternalIp();
         Program.Logger.Log(externalIPAddress, LoggerExt.LogExtType.Debug);
         if (!string.IsNullOrEmpty(externalIPAddress) && externalIPAddress != IPHelper.ReadIPFromFile())
         {
               IPHelper.SaveIPToFile(externalIPAddress);
               SendResetEmail(externalIPAddress);
         }
    
     }
}
Assou can see here we have a cryticacation-only one use per time-not needd if the time interval betwenenetttwochchengh.After getting the external IP addrest codrest compret with the lastininininininininininininininininininininininininininininininininininininininininindrdrdrdrdrdrdraaaaaaaadrdrdrdrdrdrdrdrdrdrdrdrdrdrdrdrdrdrdrdrdrdrdres thetheaaaaaaaaaaaaaaaathethethethethetheess.    
Points of interest
The e e e are different ways to test a windows service.Some suggest to install the service to the service to the process and debug it.That of course is an option,but not the best one,because for everry debug you will have the the the the the the the the the the the the the the the the the the the the the the the the the the the the the the the the the the proceverververververververversave server the the the the the  while(true)Thread.Sleep(1000)
     Example: 

 Collappse
 |  Copyコード
var hadler = new ExternalIPChecker();
    hadler.CallOnStart();
    
    while (true) Thread.Sleep(1000);//only while debug make the main thread to sleep infinitely

But the best option is to use the Debug directives:

#if DEBUG

                var hadler = new ExternalIPChecker();

                hadler.CallOnStart();

                while (true) Thread.Sleep(1000);//only while debug make the main thread to sleep infinitely

#else

           var servicesToRun = new ExternalIPChecker();

            ServiceBase.Run(servicesToRun);

#endif
 
When you switch from debug to release mode different sections of the code will be executed-no need for strange magic input parameters!
 
How To Install
Build the service project in release mode.Copy the release folder in the bin folder to a place where will live an will not be moved.The n the scrip in the command promput:
>sc create「ServiceName」binpath=「the absoute path to the service exe」
Please note here one very annoying.binpath="...shoud be exactly with that number of spaces.If you decided to write it binpath="...will never work!That could take You quite some time to understand if you are just following the sysntax without noticing this small detail.     If you want to remove the service:>sc delete"ServiceName"     If you want to don udate、just stop the service and copy and override the new files.     When you install the service change its configration to aut start - in the service preferences          If you want to notify more than one person-to send more email address-you can easuylity specify all the IP address in the configration using a special separator then parse the m parse and lay and lovity lovitrable the and and able the ablem and able.     Hope this was helpful and easy to understand articale!