Skip to content

Instantly share code, notes, and snippets.

@inkychris
Created April 19, 2020 17:16
Show Gist options
  • Save inkychris/1e5a6ebd3ab65a70d98757877c0d726a to your computer and use it in GitHub Desktop.
Save inkychris/1e5a6ebd3ab65a70d98757877c0d726a to your computer and use it in GitHub Desktop.
UDP Broadcast Server/Monitor - Powershell
param(
[ValidateSet("serve", "monitor")]
[Parameter(Mandatory = $true)]
[string]$Command,
[string]$Address = "255.255.255.255",
[int]$Port = 5606
)
if ($Command -eq "serve") {
$IP = [System.Net.Dns]::GetHostAddresses($Address)
$EndPoints = New-Object System.Net.IPEndPoint([System.Net.IPAddress]::Parse($IP), $Port)
$Client = New-Object System.Net.Sockets.UDPClient
try {
while($true) {
$Message = "$(Get-Date)"
$EncodedText = [Text.Encoding]::ASCII.GetBytes($Message)
$SendMessage = $Client.Send($EncodedText, $EncodedText.Length, $EndPoints)
Write-Host "`r> $Message" -NoNewLine
sleep 1
}
} finally {
$Client.Close()
}
}
elseif ($Command -eq "monitor") {
$EndPoint = New-Object System.Net.IPEndPoint([IPAddress]::Any, $Port)
$Client = New-Object System.Net.Sockets.UDPClient($Port)
$Client.Client.ReceiveTimeout = 100
try {
while ($true) {
try {
$Reponse = $Client.Receive([Ref]$EndPoint)
$Message = [Text.Encoding]::ASCII.GetString($Reponse)
Write-Host "`r> $($EndPoint.address.ToString()): $Message" -NoNewLine
} catch [System.Net.Sockets.SocketException] { continue }
}
} finally {
$Client.Close()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment