Here is my code:
$client = new-object net.sockets.udpclient(0) write-host "You are $(((ipconfig) -match 'IPv').split(':')[1].trim()):$($client.client.localendpoint.port)" $peerIP = read-host "Peer IP address" $peerPort = read-host "Peer port" $send = [text.encoding]::ascii.getbytes("heyo") [void] $client.send($send, $send.length, $peerIP, $peerPort) $ipep = new-object net.ipendpoint([net.ipaddress]::any, 0) $receive = $client.receive([ref]$ipep) echo ([text.encoding]::ascii.getstring($receive)) $client.close()
It performs the following actions:
- Creates a UDPClient with an automatically assigned port (0).
- Gets the local IP address, and UDPClient automatically assigns the port and displays it to the user.
- Retrieves the IP address and port of a peer-to-peer network from a user.
- Converts the string "heyo" from ASCII encoding to an array of bytes and sends it to the peer. (I believe he will sit there at the equal end until he is βaccepted,β even for a few seconds.)
- Creates an IPEndPoint that receives a UDP packet from any IP address and any port (0).
- Retrieves any data sent from the peer as a new byte array, with this IPEndPoint as the reference parameter (which now saves the source code of the received packet).
- Converts the resulting byte array to an ASCII encoded string and prints it.
- Closes UDPClient. (Be sure to do this, otherwise the resources will be saved (until you restart the PS)!
The beauty of this script is that it is very simple and straightforward, and you can use it either with localhost / 127.0.0.1 (in two separate PowerShell windows), or with an external IP address, which, if it is a local IP address, You already know, because the local IP address is printed for you by the script.
Note that there are SendAsync and ReceiveAsync for UDPClient, but there is no timeout for them. Some people have prepared complex workarounds for this, but you can also just use the PowerShell Start-Job commands and other *-Job and put the receive loop in a separate startup code.
source share