In this post, I am going to cover some more of the DownloadString() method of the .Net WebClient that we briefly touched on in my earlier post.
I am going to show you a function that will return your current external/public IP address.
There a numerous services out there that allow a user to get their external IP Address, most have two flavours, one which will return a nicely formatted page with text like “Your IP address is 123.123.123.123” whilst others are designed for automation and will simply return a plain text formatted page with only the IP address 123.123.123.123. Of course, you could make your own service and host it somewhere yourself. It is very simple to make your own page which can do this with a single line of C# in a ASP.Net page (.ASPX), C# code in a Web Event Handler (.ASHX), PHP page or even classic ASP (.ASP) page.
A later post will cover making your own page, for today, we will test with one of the already existing services listed below:
Let’s start by writing a function that will perform the following:
Let’s take a look at a function which would return our current IP address:
So we can see this is a pretty standard PowerShell Function. The function starts off with a param definition, there is a single parameter $ipcheckurl, for once I am being a nice programmer and specifying the type as a String. This is an optional parameter, and if there is no value for this parameter provided we will use the value of http://icanhazip.com .
The body of the function is pretty simple. Let’s make a WebClient object, then we will set the UserAgent header to that of a Windows Internet Explorer UserAgent, and finally, we call the DownloadString method, specifying our URL and return it to the calling code.
That’s all pretty simple right?
Before we continue, notice I didn’t add any error handling? That is because if anything goes wrong, I want the calling code to know that something has gone wrong. anything calling this will need to handle any errors that might occur (for example, page not found, name could not be resolved, server busy etc).
Now lets look at a script we could use to monitor our external IP address, it will perform the following:
Lets Take a look:
I am not going to go into much detail, this is a pretty simple script. I am assuming that the function that was previously discussed is available, you could put it into either a module or just defined in the script file.
So, now you know how to watch for your external IP address changing!