Tuesday, July 08, 2008

Get-PublicIp4Address.ps1

Using dyndns' checkip page and two lines of PowerShell, you can get your public IP address easily -

$wc=New-Object net.webclient
$wc.downloadstring("http://checkip.dyndns.com") -replace "[^\d\.]"



Note the use of -replace with a single argument. This removes the pattern and works like -replace "string","". I also really like that you can call a method and work directly on the output.



You could turn this into a one-liner -




(New-Object net.webclient).downloadstring("http://checkip.dyndns.com") -replace "[^\d\.]"



but I think the two-line version is much easier to read, so I'll stick to that.



PS. Regex interpreration: Remove everything not (^) a digit (\d) or a dot (\.). The webpage returns a string like "Current IP Address: 10.1.2.3" and I wanted to get rid of the extra stuff.

2 comments:

Ziemek Borowski said...

nice, but when You use Proxy sever You can get strange effects. checkip.dyndns.com interpret HTTP variable HTTP_X_FORWARDED_FOR.

Per Østergaard said...

Hi Ziemek

Thanks for the comment, I wasn't aware of that. I have no proxy, so I cannot test it myself.

Per