Powershell create multicast listener
Forum rules
Do not post any licensing information in this forum.
Any code longer than three lines should be added as code using the 'Select Code' dropdown menu or attached as a file.
Do not post any licensing information in this forum.
Any code longer than three lines should be added as code using the 'Select Code' dropdown menu or attached as a file.
Re: Powershell create multicast listener
First I want to thank everyone for there help. I figured this out and thought I would share the script just in case anyone wants to do the same thing. My only issue is making it time out if no data is present.
Code: Select all
function Multicast-Listen([int]$Port, [string]$IPMCastAddress, [string]$IPLocalAddress){
#First create the multicast socket.
$mCastSocket = New-Object System.Net.Sockets.Socket([System.Net.Sockets.AddressFamily]::InterNetwork, [System.Net.Sockets.SocketType]::Dgram, [System.Net.Sockets.ProtocolType]::Udp)
#Now create the local endpoint using the address and port passed in.
$locEndPoint = New-Object System.Net.IPEndPoint([System.Net.IPAddress]::Parse($IPLocalAddress), $Port)
#Create the remote endpoint (any)
$remEndPoint = New-Object System.Net.IPEndPoint([System.Net.IPAddress]::Parse([Net.IPAddress]::Any),0)
#I'm not sure why, but if you don't cast this to an EndPoint object, it won't work
$remEndPoint = [System.Net.EndPoint] $remEndPoint
#Define our MulticastOption object (mcast address etc.)
$mCastOption = New-Object System.Net.Sockets.MulticastOption([System.Net.IPAddress]::Parse($IPMCastAddress), [System.Net.IPAddress]::Parse($IPLocalAddress))
$mCastSocket.SetSocketOption([System.Net.Sockets.SocketOptionLevel]::IP, [System.Net.Sockets.SocketOptionName]::AddMembership, $mCastOption)
#Bind the socket to the endpoint.
$mCastSocket.Bind($locEndPoint)
#We need an array of bytes.
$bytes = New-Object byte[] 10000
#Make sure we know what's going on.
"Waiting for a connection on port $port..." | Out-File "$(Get-Location)\debug.txt"
while ( $true ) {
$mCastSocket.Receive($bytes)
#Great! We have inbound!
"Received multicast from $($remEndPoint.ToString())" | Out-File "$(Get-Location)\debug.txt"-Append
#Get the stream.
$stream_input = $(New-Object System.Text.ASCIIEncoding).GetString($bytes, 0, $bytes.Length)
$str = New-Object String (,$stream_input)
#Write the string to the pipeline.
#$button2.Text = $str
}
$mCastSocket.Close()
"Connection closed." | Out-File .\debug.txt
}
Multicast-Listen -IPMCastAddress 224.0.0.1 -Port 1111 -IPLocalAddress 126.0.0.1
Re: Powershell create multicast listener
Use SetSocketOption "receivetimeout". This defaults to 0 which never times out.
You can also set it directly on the socket object:
$mCastSocket.ReceiveTimeout = 3000 #3 seconds
You can also set it directly on the socket object:
$mCastSocket.ReceiveTimeout = 3000 #3 seconds