Been searching for this for over an hour now, and I have not found in documentation nor in examples on the web how to enable the SO_REUSEADDR
option when working with the HttpListener
class.
My specific use case is within a Powershell script, but even if there is an answer in C#, that would be fine. This is about as cut-and-dry as it gets:
$Listener = New-Object System.Net.HttpListener
$Listener.Prefixes.Add('http://+:9999/')
Try
{
$Listener.Start()
# While loop here to handle requests; omitted for brevity
}
Catch
{
# omitted here for brevity
}
There are times where I Ctrl-C
to break out of the script while testing, and leaving the loop this way does not allow $Listener.Stop()
to be called and the socket properly closed. (Yes, I know - don't do this if it breaks things)
Normally, when I need a listening socket, I make use of SO_REUSEADDR
to handle those times where things don't clean up properly to allow me to restart my listener without having to wait 30 minutes for the port to be available again. Is there a way to do this with HttpListener
and I'm just missing it?