private async Task PerformNetworkScanAsync()
{
await Task.Run(() =>
{
string localIpAddress = GetLocalIpAddress();
if (!string.IsNullOrEmpty(localIpAddress))
{
ScanNetworkForRustServers(localIpAddress);
}
});
}
private string GetLocalIpAddress()
{
string hostName = Dns.GetHostName();
IPHostEntry hostEntry = Dns.GetHostEntry(hostName);
foreach (IPAddress ipAddress in hostEntry.AddressList)
{
if (ipAddress.AddressFamily == AddressFamily.InterNetwork)
{
return ipAddress.ToString();
}
}
return null;
}
private void ScanNetworkForRustServers(string localIpAddress)
{
string[] ipSegments = localIpAddress.Split('.');
if (ipSegments.Length != 4)
{
resultsListBox.Items.Add("Invalid local IP format.");
return;
}
string baseIpAddress = $"{ipSegments[0]}.{ipSegments[1]}.{ipSegments[2]}";
for (int i = 1; i <= 255; i++)
{
string ipAddress = $"{baseIpAddress}.{i}";
if (CheckPort(ipAddress, 28015))
{
resultsListBox.Items.Add($"Server found: {ipAddress}:28015");
}
}
}
private bool CheckPort(string ipAddress, int port)
{
using (TcpClient tcpClient = new TcpClient())
{
try
{
tcpClient.Connect(ipAddress, port);
return true; // Port is open
}
catch (SocketException)
{
return false; // Port is closed
}
}
}