Here's 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 does the following:
- Creates a UDPClient with an automatically assigned port (0).
- Gets the local IP address and UDPClient's automatically assigned port and prints this out to the user.
- Retrieves the peer's IP address and port from the user.
- Converts string "heyo" from ASCII-encoding into a byte array and sends it to the peer. (I believe it will sit there on the peer's end until it is "received", even for some number of seconds.)
- Creates an IPEndPoint that takes a UDP packet from any IP address and any port (0).
- Receives whatever data was sent from the peer as a new byte array with that IPEndPoint as a reference parameter (that now stores the origin of the received packet).
- Converts the received byte array to an ASCII-encoded string and prints it.
- Closes the UDPClient. (Make sure to do this; otherwise, the resources will persist (until you restart PS)!)
The beauty of this script is that it's very simple and straightforward and you can use it both with localhost
/127.0.0.1
(in two separate PowerShell windows) or with an external IP address, which, if it's a local IP address, you will know already because the local IP is printed out for you by the script.
Note that there is a SendAsync and a ReceiveAsync for UDPClient, but there is no timeout for them. Some people have cooked up complicated workarounds for this, but you can also just use PowerShell's Start-Job
and other *-Job
commands and put a receive loop in separately run code.