RSE/Backend/Helper/TcpClientHelper.cs

31 lines
991 B
C#

using System.Net;
using System.Net.Sockets;
using Models.Model.Backend;
namespace Backend.Helper;
public static class TcpClientHelper
{
public static (int, int) CheckPort(Ip ip, params int[] ports)
{
// This would be way cleaner if the TcpClient didn't throw an exception if the destination couldn't be reached,
// and it would just return a result.error, for example.
for (int i = 0; i < ports.Length; i++) {
using Socket socket = new(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
socket.SendTimeout = 250;
try
{
socket.Connect(new IPEndPoint(IPAddress.Parse(ip.ToString()), ports[i]));
socket.Close();
// If the connection is not successful, update the ports array with 0.
}
catch
{
ports[i] = 0;
}
}
return (ports[0], ports[1]);
}
}