Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@gregmac
Last active April 24, 2017 15:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gregmac/724c971d4aa36c8c1061f60eee837bf4 to your computer and use it in GitHub Desktop.
Save gregmac/724c971d4aa36c8c1061f60eee837bf4 to your computer and use it in GitHub Desktop.
Find RaspberryPi's on local network from Windows
# Powershell script
$nic=gwmi -computer . -class "win32_networkadapterconfiguration"|Where-Object{$_.defaultIPGateway -ne $null}
$IP=$nic.ipaddress|select-object -first 1;$Mask=$nic.ipsubnet|select-object -first 1;$IPInt=([Net.IPAddress]$IP).Address;$MaskInt=([Net.IPAddress]$Mask).Address;$start=($IPInt -band $MaskInt);$end=($IPInt -bor(-bnot [uint32]$MaskInt))-16777216;
Write-Host "Scanning $IP/$Mask...";while($start -lt $end){$start += 16777216;Test-Connection (new-object System.Net.IPAddress $start).ToString() -Count 1 -AsJob|Out-Null};Start-Sleep 1;
Write-Host "Looking up hostnames..";Get-NetNeighbor|Where-Object{$_.LinkLayerAddress.StartsWith("B8-27-EB")}|ForEacH { [PSCustomObject]@{IP = $_.IPAddress; MAC = $_.LinkLayerAddress; Host = [System.Net.Dns]::GetHostByAddress($_.IPAddress).HostName}}
# find local IP with default gateway
$nic=gwmi -computer . -class "win32_networkadapterconfiguration" | Where-Object{$_.defaultIPGateway -ne $null}
# get IP and subnet mask
$IP=$nic.ipaddress|select-object -first 1;
$Mask=$nic.ipsubnet|select-object -first 1;
# Note: uses obsolete and weird .NET IPAddress integer math
$IPInt=([Net.IPAddress]$IP).Address;
$MaskInt=([Net.IPAddress]$Mask).Address;
$start=($IPInt -band $MaskInt);
$end=($IPInt -bor(-bnot [uint32]$MaskInt))-16777216;
# ping each IP
Write-Host "Scanning $IP/$Mask...";
while($start -lt $end) {
$start += 16777216;
Test-Connection (new-object System.Net.IPAddress $start).ToString() -Count 1 -AsJob|Out-Null
};
# wait a second to ensure ARP tables get populated
Start-Sleep 1;
# look through ARP cache
Write-Host "Looking up hostnames..";
Get-NetNeighbor | Where-Object{$_.LinkLayerAddress.StartsWith("B8-27-EB")} | ForEacH {
[PSCustomObject]@{
IP = $_.IPAddress;
MAC = $_.LinkLayerAddress;
# look up hostname
Host = [System.Net.Dns]::GetHostByAddress($_.IPAddress).HostName
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment