Skip to content

Commit

Permalink
Allow to specify the local endpoint for HttpListener (#398)
Browse files Browse the repository at this point in the history
  • Loading branch information
Alex-111 authored Jul 27, 2023
1 parent 09ccc7b commit 2603913
Showing 1 changed file with 15 additions and 4 deletions.
19 changes: 15 additions & 4 deletions nanoFramework.System.Net.Http/Http/System.Net.HttpListener.cs
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,11 @@ public class HttpListener
/// </summary>
private int m_Port;

/// <summary>
/// the local endpoint to bind the socket to. if Null the default is used
/// </summary>
private IPAddress m_localEndpointIP;

/// <summary>
/// Indicates whether the listener is started and is currently accepting
/// connections.
Expand Down Expand Up @@ -136,13 +141,15 @@ public HttpListener(string prefix)
/// <param name="port">The port to start listening on. If -1, the
/// default port is used (port 80 for http, or port 443 for https).
/// </param>
/// <param name="localEndpointIP"> The local endpoint to bind the socket to. If Null the default is used
/// </param>
/// <remarks>In the desktop version of .NET, the constructor for this
/// class has no arguments.</remarks>
public HttpListener(string prefix, int port)
public HttpListener(string prefix, int port, IPAddress localEndpointIP = null)
{
lockObj = new object();

InitListener(prefix, port);
InitListener(prefix, port, localEndpointIP);
}

/// <summary>
Expand All @@ -153,7 +160,7 @@ public HttpListener(string prefix, int port)
/// <param name="port">The port to start listening on. If -1, the
/// default port is used (port 80 for http, or port 443 for https).
/// </param>
private void InitListener(string prefix, int port)
private void InitListener(string prefix, int port, IPAddress localEndpointIp = null)
{
switch (prefix.ToLower())
{
Expand All @@ -179,6 +186,10 @@ private void InitListener(string prefix, int port)
m_Port = port;
}

if (localEndpointIp != null)
{
m_localEndpointIP = localEndpointIp;
}
// Default members initialization
m_maxResponseHeadersLen = 4;
m_RequestArrived = new AutoResetEvent(false);
Expand Down Expand Up @@ -494,7 +505,7 @@ public void Start()
// empty on purpose
}

IPAddress addr = IPAddress.GetDefaultLocalAddress();
IPAddress addr = m_localEndpointIP ?? IPAddress.GetDefaultLocalAddress();

IPEndPoint endPoint = new IPEndPoint(addr, m_Port);
m_listener.Bind(endPoint);
Expand Down

0 comments on commit 2603913

Please sign in to comment.