Re: Powershell create multicast listener
Posted: Mon Nov 20, 2017 2:00 pm
Can't help you with this. You will have to learn how to use a multicast port and how to decode what is being sent. We cannot help you with this.
SAPIEN Technologies Inc.
https://www.sapien.com/forums/
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