Skip to content

Instantly share code, notes, and snippets.

@lostmsu
Created December 23, 2016 08:06
Show Gist options
  • Save lostmsu/aec6fecfe5b057206d7707031ef065f0 to your computer and use it in GitHub Desktop.
Save lostmsu/aec6fecfe5b057206d7707031ef065f0 to your computer and use it in GitHub Desktop.
Simple dynamic DNS client for namecheap. Looks for files in \ProgramData\DynDns in form of <yourdomain>.namecheap, containing dyndns password. Can be used with csi (C# script) and Task Scheduler
using System.Diagnostics;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Security.AccessControl;
IPAddress GetMyExternalIpAddress() {
var dnsQuery = new ProcessStartInfo("nslookup", "myip.opendns.com. resolver1.opendns.com")
{
RedirectStandardOutput = true,
UseShellExecute = false,
};
var lookup = Process.Start(dnsQuery);
var lookupResult = lookup.StandardOutput.ReadToEnd().Split('\n');
bool answer = false;
foreach(var line in lookupResult)
{
if (line.Contains("Name:"))
{
System.Console.WriteLine("Got IP!");
answer = true;
}
else if (!answer)
continue;
if (line.StartsWith("Address:"))
return IPAddress.Parse(line.Substring("Address:".Length).Trim());
}
throw new SocketException();
}
var appData = System.Environment.GetFolderPath(System.Environment.SpecialFolder.CommonApplicationData);
var dynDnsFolder = Path.Combine(appData, "DynDns");
var adminsOnly = new DirectorySecurity();
adminsOnly.AddAccessRule(new FileSystemAccessRule(@"BUILTIN\Administrators", FileSystemRights.FullControl,
InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit,
PropagationFlags.None, AccessControlType.Allow));
var hosts = Directory.CreateDirectory(dynDnsFolder, adminsOnly);
void NamecheapUpdateIp(IPAddress newIp, string hostName, string hostPassword) {
var request = HttpWebRequest.Create($"https://dynamicdns.park-your-domain.com/update?host=@&domain={hostName}&password={hostPassword.TrimEnd('\n')}&ip={newIp}");
request.GetResponse();
}
IPAddress myIp = GetMyExternalIpAddress();
foreach(var hostFile in hosts.EnumerateFiles())
{
if (".namecheap".Equals(hostFile.Extension, System.StringComparison.OrdinalIgnoreCase))
{
var host = Path.GetFileNameWithoutExtension(hostFile.Name);
NamecheapUpdateIp(myIp, host, File.ReadAllText(hostFile.FullName));
System.Console.WriteLine($"Updated {host} to {myIp}");
}
else
System.Console.Error.WriteLine("Unrecognized service type: " + hostFile.Extension);
}
@lostmsu
Copy link
Author

lostmsu commented Dec 23, 2016

P.S. park-your-domain.com is owned by Namecheap. Reverse engineered from Namecheap official DynDns client.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment