This repository has been archived by the owner on May 6, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 4
/
BackgroundUpdater.cs
102 lines (88 loc) · 2.71 KB
/
BackgroundUpdater.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading;
namespace DynDNSUpdater
{
class BackgroundUpdater
{
private bool _continue;
private Thread worker;
public string ServiceUrl;
public string Domain;
public string Username;
public string Password;
public int UpdateInterval;
public string LastErrorMessage;
public EventHandler ErrorCallback;
public EventHandler SuccessCallback;
public BackgroundUpdater()
{
UpdateInterval = 60;
worker = new Thread(DoWork);
}
public void Start()
{
_continue = true;
worker.Start();
}
public void Stop()
{
_continue = false;
worker.Abort();
}
public bool IsRunning()
{
return worker.IsAlive;
}
public void DoWork()
{
Debug.WriteLine("Thread starting");
while(_continue) {
try
{
Debug.WriteLine("Updating "+ Domain +" with public IP " + getPublicIPAddress());
updateIP();
SuccessCallback(this, null);
Debug.WriteLine("OK");
Thread.Sleep(UpdateInterval * 1000);
}
catch (Exception ex)
{
Debug.WriteLine("Erreur : "+ex.Message);
if (ErrorCallback != null)
{
Debug.WriteLine(ex.Message);
LastErrorMessage = ex.Message;
ErrorCallback(this, null);
}
Thread.Sleep(2000);
}
}
Debug.WriteLine("Thread stopped");
}
private string getPublicIPAddress()
{
string addr = httpGet("http://ipv4.icanhazip.com");
return addr.Replace("\n", "");
}
private void updateIP()
{
string ipAddr = getPublicIPAddress();
string url = "http://" + ServiceUrl + "/nic/update?system=dyndns&hostname=" + Domain + "&myip=" + getPublicIPAddress();
httpGet(url, new NetworkCredential(Username, Password));
}
private string httpGet(string url, NetworkCredential credentials = null)
{
WebClient request = new WebClient();
if (credentials != null)
{
request.Credentials = credentials;
}
return request.DownloadString(url);
}
}
}