-
Notifications
You must be signed in to change notification settings - Fork 0
/
DNSUpdater.cs
223 lines (199 loc) · 7.9 KB
/
DNSUpdater.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
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
using System;
using System.Diagnostics;
using System.Net;
using System.Net.Http;
using System.Net.Sockets;
using System.ServiceProcess;
using System.Text;
using System.Threading.Tasks;
using System.Timers;
namespace DNSUpdaterService
{
public partial class DNSUpdater : ServiceBase
{
private Timer timer;
private string apiKey = "#YourArvanCloudAPiKey#";
private string domainId = "#YourDmoainID#";
private string baseUrl = "https://napi.arvancloud.ir/cdn/4.0/domains/malijack.icu/dns-records/";
public DNSUpdater()
{
InitializeComponent();
}
protected override void OnStart(string[] args)
{
// Start a timer to periodically update the DNS record
timer = new Timer();
timer.Interval = TimeSpan.FromMinutes(30).TotalMilliseconds; // Adjust the interval as needed
timer.Elapsed += TimerElapsed;
timer.Start();
}
protected override void OnStop()
{
// Stop the timer when the service is stopped
timer.Stop();
timer.Dispose();
}
private async void TimerElapsed(object sender, ElapsedEventArgs e)
{
Log("Timer elapsed. Attempting to update DNS record.");
// Get the public IP address
string publicIp = await GetPublicIpAddressAsync();
Log($"Retrieved public IP address: {publicIp}");
// Get the current IP address of the hostname "nima.malijack.icu"
string currentDnsIp = await GetDnsIpAddressAsync();
Log($"Retrieved DNS IP address: {currentDnsIp}");
// Compare the public IP with the DNS IP
if (publicIp != currentDnsIp)
{
// Create the JSON payload
string jsonPayload = $@"
{{
""type"": ""a"",
""name"": ""#YourSubDomain#"",
""value"": [
{{
""ip"": ""{publicIp}"",
""port"": null,
""weight"": 100,
""country"": ""IR""
}}
],
""ttl"": 120,
""cloud"": false,
""upstream_https"": ""default"",
""ip_filter_mode"": {{
""count"": ""single"",
""order"": ""none"",
""geo_filter"": ""none""
}}
}}";
bool success = await UpdateDnsRecordAsync(jsonPayload);
if (success)
{
Log("DNS record update successful.");
}
else
{
Log("DNS record update failed.");
}
}
else
{
Log("Public IP address matches DNS IP address. Skipping DNS update.");
}
}
private async Task<bool> UpdateDnsRecordAsync(string jsonPayload)
{
using (HttpClient httpClient = new HttpClient())
{
string url = $"{baseUrl}{domainId}";
var request = new HttpRequestMessage(HttpMethod.Put, url);
request.Headers.Add("Authorization", $"ApiKey {apiKey}");
request.Content = new StringContent(jsonPayload, Encoding.UTF8, "application/json");
try
{
var response = await httpClient.SendAsync(request);
if (response.IsSuccessStatusCode)
{
return true;
}
else
{
Log($"API request failed with status code: {response.StatusCode}");
return false;
}
}
catch (HttpRequestException ex)
{
Log($"API request failed: {ex.Message}");
return false;
}
}
}
private async Task<string> GetPublicIpAddressAsync()
{
string[] ipServices = {
"https://httpbin.org/ip",
"https://icanhazip.com",
"http://checkip.dyndns.org"
};
using (HttpClient httpClient = new HttpClient())
{
foreach (string ipService in ipServices)
{
try
{
var response = await httpClient.GetStringAsync(ipService);
// Parse the response based on the service
if (ipService.Contains("httpbin.org"))
{
dynamic json = Newtonsoft.Json.JsonConvert.DeserializeObject(response);
return json.origin;
}
else if (ipService.Contains("icanhazip.com"))
{
return response.Trim();
}
else if (ipService.Contains("checkip.dyndns.org"))
{
int startIndex = response.IndexOf("Current IP Address: ") + 20;
int endIndex = response.IndexOf("</body>");
return response.Substring(startIndex, endIndex - startIndex);
}
}
catch (Exception ex)
{
Log($"IP retrieval failed for {ipService}: {ex.Message}");
}
}
// Return a default value or handle the failure as needed
return "Unable to retrieve public IP address.";
}
}
private async Task<string> GetDnsIpAddressAsync()
{
// Resolve the DNS hostname to get its IP address
try
{
var hostEntry = await Dns.GetHostEntryAsync("#YourFullDomain#");
if (hostEntry.AddressList.Length > 0)
{
return hostEntry.AddressList[0].ToString();
}
else
{
Log("Failed to resolve DNS hostname to an IP address.");
return null;
}
}
catch (Exception ex)
{
Log($"Failed to resolve DNS hostname: {ex.Message}");
return null;
}
}
private HttpClient CreateHttpClientWithLocalEndpoint()
{
// Specify the local endpoint (IP address and port) for the HttpClient
var localEndpoint = new IPEndPoint(IPAddress.Parse("#Your InterFace IP#"), 0);
// Create a custom HttpClient with a specific local endpoint
var httpClientHandler = new HttpClientHandler
{
UseDefaultCredentials = false,
Proxy = null,
UseProxy = false
};
var customHttpClient = new HttpClient(httpClientHandler);
customHttpClient.DefaultRequestHeaders.Add("User-Agent", "Your_User_Agent"); // Add a user agent header if needed
customHttpClient.DefaultRequestHeaders.Add("Authorization", $"ApiKey {apiKey}");
// Bind the HttpClient to the specified local endpoint
var bindingProperty = customHttpClient.GetType().GetProperty("LocalEndPoint");
bindingProperty.SetValue(customHttpClient, localEndpoint);
return customHttpClient;
}
private void Log(string message)
{
EventLog.WriteEntry("DNSUpdaterService", message, EventLogEntryType.Information);
}
}
}