'Finding all TCPListeners in a subnet listening on a specific port/Having all of them respond to a broadcast message
I am trying to get all the TCPListener(s) of my application that are running on a specified port so I can display them in a server browser, I thought I could just send a udp packet to the broadcast with a message with the ip of the asking computer and have them respond to it once they see it. I don't want to manually go through all the possible ips in the subnet and try connect to them with a tcpclient at the specify port just to do it, I want them to respond to the message. Is that possible ? For reference the listener code looks like this:
public async Task ListenAsync()
{
listener.Start();
while (!_serverShouldClose)
{
var handleClientsTask = HandleClientsAsync();
var sendAliveTask = SendAlive();
if (listener.Pending())
{
var clientTask = listener.AcceptTcpClientAsync();
var client = await clientTask;
await client.GetStream().WriteAsync(Encoding.UTF8.GetBytes("Hello from server\n"));
_connectedClients.Add(client);
}
await Task.WhenAll(sendAliveTask, handleClientsTask);
}
listener.Stop();
}
public async Task HandleClientsAsync()
{
byte[] buffer = new byte[1024];
foreach (var client in _connectedClients)
{
if (!client.Connected)
{
_connectedClients.Remove(client);
client.Close();
client.Dispose();
continue;
}
if(client.GetStream().DataAvailable)
{
await client.GetStream().ReadAsync(buffer);
if (Encoding.ASCII.GetString(buffer).Contains("gib settings"))
{
await client.GetStream().WriteAsync(Encoding.ASCII.GetBytes(JsonSerializer.Serialize(_settings)));
}
}
}
}
Solution 1:[1]
Is that possible ?
Technically, yes.
Personally, I would do this via Powershell or some other management-level solution like Windows Remote Management / WMI. That way you could just ask the OS directly, and then filter open sockets by port.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Stephen Cleary |
