Monday, November 12, 2012

PowerShell: Resolve Remote Host and IPv4 Address

Update: I found the script block only works on local hosts.  As such, I found another way to get the remote host name and IP via PowerShellASP.

<%$ipaddress = [net.IPAddress]::Parse($request.UserHostAddress)%>

<%$UserHostname = [System.Net.Dns]::gethostentry($ipaddress.ipaddresstostring)%>
<%$UserHostname = $UserHostName.hostname -replace ".domain.suffix",""%>
Your Computers IP:<%=$ipaddress%> & Host Name:<%=$userhostname%><br><hr>

Click here to find your public IP address without using PowerShellASP.


I don't know if this helps but I've been working on a way to obtain the remote host name and IP for my PowerShellASP site.  Every several searches and testing, I found .net commands which extract the host name and an IPv4 adddress:
#PowerShell Script
$remotehostname = [system.net.dns]::gethostname()
#I noticed the ScopeID of IPv4 addresses is always $null, so I used that to find the IPv4 address
$remotehostipv4 = [system.net.dns]::gethostaddresses($remote)|?{$_.scopeid -eq $null}|%{$_.ipaddresstostring}
#Sample line displaying the host and IP.
$remotehostname,$remotehostipv4
Then I applied them to a test PowerShellASP file:



<%$remote = [system.net.dns]::gethostname()%>

<%$remoteip = [system.net.dns]::gethostaddresses($remote)|?{$_.scopeid -eq $null}|%{$_.ipaddresstostring}%>

Remote IP: <%=$remoteip%><br>
Remote: <%=$remote%>

By obtaining the remote host name and IP (a PowerShellASP website visiting computer), I can create a remote connection and run PowerShell commands on the remote host for the user.  By default, PowerShellASP will run all commands on the server, meaning that a request to see how much hard drive space is left will be ran on the server.  This will return the server's remaining hard drive space result to the remote user.  Frankly, the user doesn't care about the servers hard drives and really wants to know about their own hard drives.  To perform this request, the web server has to create a remote WMI connection and run the command. Having the remote host information allows this to happen.