In the previous article, the Send-tcpmessage and receive-tcpmessage two functions were created in the Psnet toolset to implement the function of sending and receiving TCP message packets through PowerShell, with the TCP packet sent and received, Naturally without the sending and receiving of UDP message packets, this article will introduce the method of sending and receiving UDP message packets via PowerShell.
To match the previous Psnet assembly, continue to expand based on this assembly, create the Udpop directory under $env:psspace\psnet, In which you create the RECEIVE-UDPMESSAGE.PS1 and send-udpmessage.ps1 two files, the code is inserted later.
Add a reference to the two script files in $env:psspace\psnet\psnet.psm1, as follows:
Copy Code code as follows:
. $env:P Sspace/psnet/tcpop/receive-udpmessage.ps1
. $env:P Sspace/psnet/tcpop/send-udpmessage.ps1
Note that these two lines of code need to be preceded by the Export-modulemember-function * code that already exists in PSNET.PSM1 to ensure that the functions contained in the introduced script file can be registered as members of the assembly module. So that it can be identified by the PowerShell process.
The following code is attached:
Copy Code code as follows:
===== FileName: receive-udpmessage.ps1=====
Function Receive-udpmessage
{
Param ([Validatenotnullorempty ()]
[INT] $Port)
Try
{
$EndPoint = New-object System.Net.IPEndPoint ([System.net.ipaddress]::loopback, $Port)
$UDPClient = New-object System.Net.Sockets.UDPClient ($Port)
$ReceiveMessage = $UDPClient. Receive ([System.Management.Automation.PSReference] $EndPoint)
[System.text.encoding]::ascii. GetString ($ReceiveMessage)
}
catch{}
}
Copy Code code as follows:
===== FileName: send-udpmessage.ps1=====
Function Send-udpmessage
{
Param ([Validatenotnullorempty ()]
[String] $EndPoint,
[INT] $Port,
[String] $Message)
$IP = [System.net.dns]::gethostaddresses ($EndPoint)
$Address = [System.Net.IPAddress]::P arse ($IP)
$EndPoints = New-object System.Net.IPEndPoint ($Address, $Port)
$Socket = New-object System.Net.Sockets.UDPClient
$EncodedText = [Text.encoding]::ascii. GetBytes ($Message)
$SendMessage = $Socket. Send ($EncodedText, $EncodedText. Length, $EndPoints)
$Socket. Close ()
}
Start two PowerShell processes to import psnet modules separately:
Copy Code code as follows:
Import-module $env:P sspace\psnet
First run Receive-udpmessage to monitor the port:
Copy Code code as follows:
It then sends a message to the port specified above through the Receive-udpmessage function:
Copy Code code as follows:
Send-udpmessage 127.0.0.1 8080 "This are a UDP message Send from psnet!"
The message content is displayed in the previous window after it is sent.
In the example in this article, in order to display the send effect, the string is transmitted in the form of ASCII characters, but the actual situation is usually the hexadecimal data form, in subsequent articles we will improve the example of this article to adapt to the actual work needs.