Introduction
This is a simple snippet to listen for DHCP Request messages that come from Amazon Dash buttons; for the purpose of Dash button automation. Most solutions require either intercepting the request to button's request to Amazon or pinging a known IP address. Both of these solutions tend to require additional setup of the router to detect and redirect the button request, or a static DHCP reservation to keep the dash button's IP address consistent. Both of the aforementioned solutions can have as much as a 5.5 second delay between when the button is first pressed to when it is detected. This method of intercepting the broadcast DHCP Request can take as little as 2.5 seconds. Previously, this code only looked for DHCP Discover messages, however some dash buttons do not always broadcast this packet.
Using the Code
You will need to know the mac address of the dash button so that the filter can be setup. The script will echo to the text file all the mac addresses that broadcast a DHCP Request address making it easy to figure out which mac address goes to which button.
$LogPath = Split-Path $MyInvocation.MyCommand.Path
Get-ChildItem "$LogPath\*.log" |
Where LastWriteTime -LT (Get-Date).AddDays(-15) | Remove-Item -Confirm:$false
$LogPathName = Join-Path -Path $LogPath
-ChildPath "$($MyInvocation.MyCommand.Name)-$(Get-Date -Format 'MM-dd-yyyy').log"
Start-Transcript $LogPathName -Append
$StartDate = (Get-Date)
$dashButtonMac = "74:75:48:9b:ad:fb"
$endpoint = new-object System.Net.IPEndPoint ([system.net.ipaddress]::any, 67)
$listenHost = new-object System.Net.Sockets.UdpClient
$listenHost.Client.SetSocketOption([System.Net.Sockets.SocketOptionLevel]::Socket,
[System.Net.Sockets.SocketOptionName]::ReuseAddress, $True);
$bindEndPoint = new-object System.Net.IPEndPoint([system.net.ipaddress]::any, 67)
$listenHost.client.Bind($bindEndPoint)
$delay = Get-Date
while($true){
$payload = $listenHost.Receive([ref] $endpoint)
if($payload[0] -eq 1 -and $payload[242] -eq 3 -and ((Get-Date) - $delay).seconds -gt 5)
{
$delay = Get-Date
$clientMac = 0,0,0,0,0,0
[array]::Copy($payload, 28,$clientMac,0,6)
for($i = 0; $i -lt $clientMac.Count; $i++){
$clientMac[$i] = "{0:x2}" -f $clientMac[$i]
}
$mac = $clientMac -join ':'
if($mac -eq $dashButtonMac){
Write-Output ("Dash Button has been detected : " + $mac)
}
else{
Write-Output ("Valid DHCP Request message obtained but not from Dash button : " + $mac)
}
}
Start-Sleep -Milliseconds 100
}
History
- First published working script
- Modified to look for DHCP Request in place of DHCP Discover messages