Skip to content

Instantly share code, notes, and snippets.

@hotstone
Last active July 27, 2017 06:25
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save hotstone/fdff6a808d1e03010d29 to your computer and use it in GitHub Desktop.
Save hotstone/fdff6a808d1e03010d29 to your computer and use it in GitHub Desktop.
Send UDP datagram from Powershell
function Send-Datagram {
[CmdletBinding()]
param(
[parameter(Mandatory=$true)][string] $data,
[parameter(Mandatory=$false)][string] $address="127.0.0.1",
[parameter(Mandatory=$false)][int] $port=8125
)
$ipAddress = $null
$parseResult = [System.Net.IPAddress]::TryParse($address, [ref] $ipAddress)
if ( $parseResult -eq $false )
{
$addresses = [System.Net.Dns]::GetHostAddresses($address)
if ( $addresses -eq $null )
{
throw "Unable to resolve address: $address"
}
$ipAddress = $addresses[0]
}
$endpoint = New-Object System.Net.IPEndPoint($ipAddress, $port)
$udpClient = New-Object System.Net.Sockets.UdpClient
$encodedData=[System.Text.Encoding]::ASCII.GetBytes($data)
$bytesSent=$udpClient.Send($encodedData,$encodedData.length,$endpoint)
$udpClient.Close()
}
@adracis
Copy link

adracis commented Jul 6, 2017

you forget to connect to the server before you send the payload.

  1.  `$udpClient.Connect($address,$port)`
    

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment