Is there a way to enable the SO_REUSEADDR socket option when using System.Net.HttpListener?

后端 未结 1 1422
-上瘾入骨i
-上瘾入骨i 2020-12-22 00:58

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 workin

相关标签:
1条回答
  • 2020-12-22 01:40

    No, you can't use SO_REUSEADDR with HttpListener.

    The reason is that the HttpListener doesn't actually manage the underlying socket - it simply registers application-level prefixes with the HTTP.sys driver, who in turn manages the underlying connection.

    To use SO_REUSEADDR, you could create a TcpListener and set the socket option on the underlying socket (accessible through the Server property) with SetSocketOption():

    $TcpListener = New-Object System.Net.Sockets.TcpListener 9999
    $TcpListener.Server.SetSocketOption("Socket", "ReuseAddress", 1)
    $TcpListener.Start()
    

    But now you have to implement all the convenient things that HttpListener provides on you own (header parsing, content validation etc.).


    That being said, this may solve the practical issue you face:

    try{
        $Listener.Start()
    }
    catch{
    }
    finally{
        $Listener.Stop()
        $Listener.Dispose()
    }
    

    (don't paste this into you prompt/ISE, you need to save this to a script, or enclose in a script block for finally to be evaluated properly on interruption)

    0 讨论(0)
提交回复
热议问题