Create ddns client notes using xhr + curl.exe

Source: Internet
Author: User
Tags http authentication
Document directory
  • 1. How do I know my IP address? & Xhr Creation
  • Ii. Business Logic
  • 3. Submit IP update
  • Iv. No summary

On the first day of September, the important thing was that the school started and the students returned to the campus. What I said below is secondary.

Yes. If you want to change the old DNS service provider, try another overseas service provider. As a webmaster, using ddns is commonplace.

I did not expect that the service provider did not provide the client. I hope it will only be provided for the time being and will be provided in the future. Fortunately, the service provider has a Web open interface, so it is proposed to be a ddns client. Through this web service interface, the HTTP basic auth authentication is adopted, and the IP address of the name server can be refreshed by submitting a single IP address segment, it is simple and feasible. Of course, it is essential to submit the domain name and password. The password of the default account is the password of the domain name. For security reasons, we do not recommend that you use the account directly, but assign a hashkey in the background as the separate password for each domain name, in this way, it is better to set a one-to-one password for each bound domain name to ensure security. Further, each domain name modifies its
In ddns, the submitted hashkeys can be different. The domain name, hash password, Web Serivce, and new IP address combination are as follows:

http://foo.bar.com:BKlud7MtMyJs2lne@dns.abc.net/update?hostname=foo.bar.com&myip=61.140.176.162

Assume that dns.abc.net is a service endpoint provided by the service provider. Theoretically, in any URL that can be entered, the task of synchronizing IP addresses can be achieved by sending the URL in the URL "input box. However, if the service provider does not provide a standard client, it will make the first-time users feel inconvenient. If they are not familiar with sending new IP addresses from URLs, standard clients are indispensable to them, the client is still required to dynamically update the domain name ". It is estimated that the service provider should eventually provide a standard client. However, it is expected that
Web Service submission method. In fact, I think it is a good practice to pass HTTP auth authentication. The task of creating a client is to detect and update the IP address of the current server. Although this IP address is not a fixed IP address, it is not long-lived and fixed. Although it can be maintained for 1 ~ 2 days, but will not notify you when the line is down, so what you do, first of all we need to detect the situation of this IP address, to ensure that once it is changed, you need to know this client. Step 2: Tell the new IP address to the remote name server. When namesever receives a message about IP address modification, it modifies the bound IP address and updates the cache within the ttls time.

Compared with the "client" solution, WebService + HTTP basicauth is simpler and safer. The "cost" is a tool that writes a monitoring IP address and sends an IP address.

The logic of this tool is very simple. We use this idea to copy a ddns. Finalizing a MS-based HTA application. It was such a simple tool that I thought would take 20 minutes to complete. However, this is just taken for granted. The internal reason is that it is because of your own drag-and-drop style, which can cause great harm to your work. For correction, it is also a personal accumulation. The notes are as follows:

1. How do I know my IP address? & Xhr Creation

This is easy to handle, including the ipconfig command can be found by many tools. The website that provides the IP address is used to query non-lan ip addresses. This method is more secure. However, the author is willing to ask a question: You can see the IP address of the website without looking at it with your eyes. What do you think of machines? Tools or functions that can read and analyze the actual response content of response. The so-called automated process, in short, is to let machines replace people's jobs.

If there is no accident, generally URL-related tasks will be associated with the modules provided by libraries such as httprequest, webrequest, and XMLHttpRequest. XMLHttpRequest has the strongest broad spectrum and can be used quickly. In practice, we must first determine the version selection, because we find that there are multiple versions of xhr (hereinafter referred to as xhr) in the system library coexist, so in accordance with the high version first principle, identify the array by traversing progid and use try ...... Catch ...... Attackers can obtain xhr objects by avoiding thrown exceptions.

I am not too sure how much try will affect the performance. In my Js library, there is a reference to the analysis by netizens, which is in the comments section.

/*** Returns the xhr object. * Note that the complete URL must start with HTTP. * @ Param {string} Referer defines the HTTP-REFERER variable, the requester's description, for example, http://www.163.com/* @ return {MSXML. serverxmlhttp} */$. xhr = function (asynccallback, Referer) {var xhr = typeof XMLHttpRequest! = 'Undefined' & New XMLHttpRequest (); If (! Xhr) {var ActiveX = ['msxml2. serverxmlhttp.5.0 ', 'msxml2. serverxmlhttp.3.0 ', 'msxml2. serverxmlhttp ', 'msxml2. xmlhttp.3.0 ', 'msxml2. XMLHTTP ', 'Microsoft. XMLHTTP ']; // try is written in the for loop. // whenever a try statement is encountered, the exception framework is placed on the stack until all try statements are completed. // If the try statement at the next level does not process an exception, the stack will be opened until a try statement is encountered. // This is a waste of performance, but the appropriate solution is not found for the moment, so this method is used. For (VAR I = 0, j = ActiveX. length; I <j; ++ I) {try {xhr = new activexobject (ActiveX [I]); break;} catch (e) {}} if (! Xhr) {throw' does not have the xhr component! ';} If (ActiveX [I]. indexof ('server ')! =-1) {// set timeout // timeouts in MS for parts of communication: Resolve, connect, send (per packet), receive (per packet) xhr. settimeouts (30000,300 00, 30000,300 00); // ignore SSL ignore all SSL errorsxhr. setoption (2, 13056);} // If (Method = "Post") {// objxmlhttp. setRequestHeader ("Content-Type", "application/X-WWW-form-urlencoded"); //} Referer & HTTP. setRequestHeader ("Referer", Referer); If (asyncca Llback & typeof (asynccallback) = 'function') {xhr. onreadystatechange = function () {If (xhr. readystate = 0) {} else if (xhr. readystate = 1) {} else if (xhr. readystate = 2) {} else if (xhr. readystate = 3) {} else if (xhr. readystate = 4 & xhr. status = 200) {asynccallback (xhr);} else if (xhr. readystate = 4 & xhr. status! = 200) {// non-OK HTTP Response var text = "HTTP Error: {0} {1} \ nfailed to grab page data from: {2 }"; TEXT = text. format (xhr. status, objxmlhttp. statustext, URL); throw text ;}} return xhr ;}

EDK. JS (Home: http://code.google.com/p/naturaljs/) package covers the commonly used MS components, including database connection, file read and write, and so on, and a superficial encapsulation, however, there are only a lot of over-engine designs for proper presentation. About the xhr object itself, it must be pointed out that in addition to the xhr object of the browser, Microsoft also provides xhr components used by serverxhr for the server. EDK adds its
Progid. In my opinion, server xhr mainly adds the "timeout" function. Although the browser cannot use server-side xhr, as far as the younger brother knows, using the setTimeout () work und can bring timeout for xhr requests, the ext library has similar implementation, and abstracts the page timer from a common method call to make it controlled by instance objects. The above is an out-of-the-box question.

Ddns uses the default timeout parameter of EDK. js. Generally, websites are stable and reliable, so you don't have to worry about timeout. Here we have prepared several IP service sites that can be queried:

  • Http://www.j4.com.tw/james/remoip.php
  • Http://www.ip38.com
  • Http://whatismyipaddress.com/

The general query site response time can meet the demand, do not need to care about a few MS Ping difference, and it is not real-time. The response results are all text strings. In this case, you can write a regular expression to extract the IP addresses in the response. For example:

IP = IP. match (/(\ D + \.) {3} \ D +/); If (IP = NULL) {throw' the server that queries the IP address has a problem. ';} Else {IP = IP [0];}
Ii. Business Logic

Here, if you say "business", it is too "grand" and the taste is too heavy. Hey hey, let's mention it. A new IP address is now known as the input condition.

If (_ IP = NULL & IP! = _ IP) {// obtain the IP address for the first time. Record the ddnsclient. _ IP = IP; logger. innerhtml + = 'initialization';} else if (_ IP! = NULL & IP! = _ IP) {// changed !!! Adsl ip changed // update the IP address here ...... Ddnsclient. _ IP = IP;} else if (_ IP! = NULL & IP = _ IP) {If (logger. innerhtml. length> 1000) {logger. innerhtml = ''; // clear innerhtml} logger. innerhtml + = '<br/> check occurred at {0}. the IP address of the current record is {1}, and the IP address of the query is {2 }. The IP address remains unchanged. '. Format (new date, _ IP, ip );}

_ IP is ddnsclient. _ IP is a static string that saves the last updated IP address. Compared with the current IP address, if the IP address is not changed, the IP address is stable. If the IP address is changed, the IP address is updated.

3. Submit IP update

Note No. xhr has completed the IP address query task, right? However, when xhr is needed to send the name server IP address later, I encountered a slightly tricky problem, which is also the reason why I spent quite some time here. First, when xhr is sent to the Web service site and the account and domain name are set, a bunch of inexplicable data is returned, which does not seem to be text data. No result is displayed, because in the HTA program, I can always use window. open () New window. unexpectedly, the IE Security Mechanism will always pop up a logon box for accounts and passwords. It is useless to click and save. Every time I asked a question, I confirmed that I had to perform manual operations. What is automatic operations?

I know that this is the HTTP authentication of the browser, and other browsers don't know if it will be so annoying-but I don't want to try it, because here I think of curl, * the famous curl tool under Nix. Is there a portable version of wood or windows? Yes! -- I immediately got back. In cmd command mode, curl-help looks at help usage first. -- this is my habit for many years. At first glance, it is very detailed. The powerful curl is really not covered. By looking at the help, we will list a lot of usage and give full play to what a string of URLs can do for input conditions. At this moment, I only need an HTTP GET command. Easy to handle! By default, other parameters are not required. See:

curl http://foo.bar.com:BKlud7MtMyJs2lne@dns.abc.net/update?hostname=foo.bar.com&myip=61.140.176.162

Hey, look at the screen, right? That's right. Show good instructions. Liunx is good! Thanks to free Linux, win is rigid, haha! All right, the next thing seems to be a piece of cake. Use wscript. Run to call the executable program and then capture the results. How to capture it? The first thought in the mind is dos redefinition of the output symbol>, which changes the default screen output to the file output. In other words, it is to save the results returned by the curl request to the file, open the disk file in HTA. If the file name is arbitrary, it is called ddns. log. It seems that the server returns good/badauth + IP. I thought about it, curl.
Is trace supported? Let's take a look at trace. I select the-trace-ASCII text. The trace result is as follows:

== Info: About to connect() to dyn.dns.he.net port 80 (#0)
== Info:   Trying 184.105.242.3... == Info: connected
== Info: Connected to dyn.dns.he.net (184.105.242.3) port 80 (#0)
== Info: Server auth using Basic with user 'forum.ajaxjs.com'
=> Send header, 248 bytes (0xf8)
0000: GET /nic/update?hostname=forum.ajaxjs.com^&myip=61.140.152.2 HTT
0040: P/1.1
0047: Authorization: Basic Zm9ydW0uYWpheGpzLmNvbTpCS2x1ZDdNdE15SnMybG5
0087: l
008a: User-Agent: curl/7.17.0 (i586-pc-mingw32msvc) libcurl/7.17.0 zli
00ca: b/1.2.2
00d3: Host: dyn.dns.he.net
00e9: Accept: */*
00f6: 
<= Recv header, 16 bytes (0x10)
0000: HTTP/1.1 200 OK.
<= Recv header, 36 bytes (0x24)
0000: Date: Tue, 30 Aug 2011 12:31:37 GMT.
<= Recv header, 26 bytes (0x1a)
0000: Server: dns.he.net v0.0.1.
<= Recv header, 43 bytes (0x2b)
0000: Email: DNS Administrator <dnsadmin@he.net>.
<= Recv header, 41 bytes (0x29)
0000: Cache-Control: no-cache, must-revalidate.
<= Recv header, 39 bytes (0x27)
0000: Expires: Wed, 29 Aug 2012 12:31:37 GMT.
<= Recv header, 19 bytes (0x13)
0000: Content-Length: 18.
<= Recv header, 24 bytes (0x18)
0000: Content-Type: text/html.
<= Recv header, 1 bytes (0x1)
0000: .
<= Recv data, 18 bytes (0x12)
0000: nochg 61.140.152.2
== Info: Connection #0 to host dyn.dns.he.net left intact
== Info: Closing connection #0

It's okay to analyze this log file. Haha. Currently, only the last and third rows are followed, indicating whether the IP address is modified or not.

The IP address is "0000: nochg 61.140.152.2". The submitted IP address is the same as the original IP address and does not need to be changed. The program uses regular/Recv data [\ s] * 0000 :(. *)/; to extract this line. I generally like to use regular expressions instead of analyzing strings.

In fact, the above process is still a little complicated, that is, at the beginning of the test, there were a bunch of messy characters, and there was no such command in the cloud, which was not the result of normal feedback, so I checked the help and tried again. After several times, it was still a mistake. I fell into a low tide again ...... Boss ...... But it's just a simple command line call. Why bother me ~ 5555. And then I analyze the characters one by one, analyze them slowly, and there is a "&" (at the querystring parameter of the URL). It turns out that this is greater than the character, in dos, it must be escaped as ^ &; otherwise, it means another ...... It's not a short time to ask yourself if you are familiar with DOS ......

Iv. No summary

Although it is a simple tool to get home, I am a very versatile person because of my poor strength. There are many things that can be completed between March 8 and September, it is very embarrassing to say that no matter whether you write code or write an article, it is like squeezing toothpaste, timeout and timeout. Ah, in short ~ In any case, I finally achieved something that is not the same as below. The general situation of the tests over the past few days is still correct.

In theory, the role of xhr and curl is basically the same, but in fact, if xhr does not have a problem with HTTP basic auth this time, it will not dispatch the xhr replacement product curl.exe. During the collection, should * nix users use curl?

The next time you want to monitor your website, you don't need to check it in 10 minutes.

Update xhr for IE:

/*** Returns the xhr object. * Note that the complete URL must start with HTTP. * @ Param {object} CFG * @ CFG {string} Referer defines the HTTP-REFERER variable, the requester's description, such as http://www.163.com/#/##.request = function (CFG) {var isnative = typeof XMLHttpRequest! = 'Undefined'; If (! Isnative) {var progid, progids = ['msxml2. serverxmlhttp.5.0 ', 'msxml2. serverxmlhttp.3.0 ', 'msxml2. serverxmlhttp ', 'msxml2. xmlhttp.6.0 ', 'msxml2. xmlhttp.3.0 ', 'msxml2. XMLHTTP ', 'Microsoft. XMLHTTP ']; // try is written in the for loop. // whenever a try statement is encountered, the exception framework is placed on the stack until all try statements are completed. // If the try statement at the next level does not process an exception, the stack will be opened until a try statement is encountered. // This is a waste of performance, but we cannot find an appropriate solution for the moment, so we have to use this hack method. For (VAR I = 0, j = progids. length; I <j; ++ I) {try {progid = progids [I]; new activexobject (progid); // No Referer at all break;} catch (E) {}}} if (! Isnative &&! Progid) {throw' has no xhr component! ';} $. Request = function (CFG) {var xhr = isnative? New XMLHttpRequest (): New activexobject (progid); If (! Xhr) {throw' An error occurred while creating the xhr object! ';} If (! CFG |! Cfg. url) {throw' does not meet the minimum parameter requirements! ';} VaR method = (CFG. ispost | cfg. Post )? "Post": "Get"; if (CFG. method) {method = cfg. method. touppercase ();} var asynccallback = cfg. FN; var isaysc; isaysc = typeof cfg. isaysc = 'undefined '? True/* asynchronous by default */: cfg. isaysc; isaysc = isaysc & asynccallback & typeof (asynccallback) = 'function'; isaysc = !! Isaysc; // FF must input a Boolean value. IE is not so strict. Xhr. Open (method, CFG. url, isaysc); If (isaysc) {// coordinates IE and places onreadystatechange after open. Xhr. onreadystatechange = function () {Switch (xhr. readystate) {Case 1: break; Case 2: break; Case 3: break; Case 4: asynccallback (xhr); // avoid ie Memory leakage $. isie & typeof setTimeout! = 'Undefined' & setTimeout (function () {xhr. onreadystatechange = new function (); xhr = NULL; Delete xhr ;}, 0); break; default: throw' communication problems! ';}}Method = 'post' & xhr. setRequestHeader ("Content-Type", "application/X-WWW-form-urlencoded"); cfg. referer & xhr. setRequestHeader ("Referer", CFG. referer); cfg. contenttype & xhr. setRequestHeader ("Content-Type", CFG. contenttype); // You may set xhr. setRequestHeader ("accept", "text/JSON"); // acceptable document format. Note that the default format is text/JSON. If (CFG. Accept & cfg. Accept! = 'Text/json') {xhr. setRequestHeader ("accept", CFG. accept);} else {xhr. setRequestHeader ("accept", 'text/json');}/* For serverside xhr only */If (! Isnative & progid. indexof ('server ')! =-1) {// set xhr for the server xhr. settimeouts (30000,300 00, 30000,300 00); // set timeout timeouts in MS for parts of communication: Resolve, connect, send (per packet), receive (per packet) xhr. setoption (2, 13056); // ignore SSL ignore all SSL errors} xhr. send (CFG. post | null); If (! Isaysc) return xhr;} return $. Request (CFG );}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.