Skip to content

Commit

Permalink
Fix: SmtpSever trying to use an unpermitted port (#33)
Browse files Browse the repository at this point in the history
* Add method trying to bind an available port
* Removed console message for CanBindPort(int port)
  • Loading branch information
axunonb committed Jun 22, 2023
1 parent 1185672 commit b641b9c
Showing 1 changed file with 21 additions and 3 deletions.
24 changes: 21 additions & 3 deletions Src/MailMergeLib.Tests/Helper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
using System.Linq;
using System.Net;
using System.Net.NetworkInformation;
using System.Net.Sockets;
using System.Reflection;

namespace MailMergeLib.Tests;
Expand Down Expand Up @@ -51,11 +52,11 @@ internal static int Compare(Stream? a, Stream? b)
/// <returns>The first free TCP port found.</returns>
/// <exception cref="InvalidCastException">If no free port could be found.</exception>

internal static int GetFreeTcpPort(int startPort = 1)
internal static int GetFreeTcpPort(int startPort = 2000)
{
for (var i = startPort; i <= Char.MaxValue; i++)
for (var i = startPort; i <= 0xFFFF; i++)
{
if (IsFreePort(i)) return i;
if (IsFreePort(i) && CanBindPort(i)) return i;
}

throw new InvalidOperationException("No free TCP port found");
Expand All @@ -68,4 +69,21 @@ private static bool IsFreePort(int port)
var openPorts = listeners.Select(item => item.Port).ToArray<int>();
return openPorts.All(openPort => openPort != port);
}

private static bool CanBindPort(int port)
{
try
{
var localEndPoint = new IPEndPoint(IPAddress.Any, port);
using var listener = new Socket(IPAddress.Any.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
listener.Bind(localEndPoint);
}
catch
{
// e.g. because of "Permission denied" or other reason
return false;
}

return true;
}
}

0 comments on commit b641b9c

Please sign in to comment.