I'm trying to build a netowrk app. I have succesfully made a server that sends and receives packages. So far, testing has been done on one computer pointing to 127.0.0.1 (No place like home). Now I want to switch to the network. How can I find computers on a LAN network that are listening to my specific port?
The service will need to listen for broadcast messages on a known port (if you want to be really well behaved you can register the program and port number with the IANA), when it hears a broadcast message it replies to the sender the server's IP and what port the service is listening for incoming connections on.
Here is a simple example from the link above, this just prints to the console who connected and on what port, but you can use this information to establish a TCP or UDP connection between the two endpoints.
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
class RecvBroadcst
{
public static void Main()
{
Socket sock = new Socket(AddressFamily.InterNetwork,
SocketType.Dgram, ProtocolType.Udp);
IPEndPoint iep = new IPEndPoint(IPAddress.Any, 9050);
sock.Bind(iep);
EndPoint ep = (EndPoint)iep;
Console.WriteLine("Ready to receive…");
byte[] data = new byte[1024];
int recv = sock.ReceiveFrom(data, ref ep);
string stringData = Encoding.ASCII.GetString(data, 0, recv);
Console.WriteLine("received: {0} from: {1}",
stringData, ep.ToString());
data = new byte[1024];
recv = sock.ReceiveFrom(data, ref ep);
stringData = Encoding.ASCII.GetString(data, 0, recv);
Console.WriteLine("received: {0} from: {1}",
stringData, ep.ToString());
sock.Close();
}
}
As a psudo example here is the sequence of events on how I would do it.
For this example lets say we have a network with a IP of 192.168.1.0
and a subnet of 255.255.255.0
. We have two servers, Server1
at 192.168.1.2
with the service listening on port 1234
, and Server2
at 192.168.1.3
with a port of 4567
for the service. Both are listing on port 3000
for broadcast messages. The client connecting will be at the IP 192.168.1.4
192.168.1.255:3000
) using the same port to send as he is listening on. He sends some kind of payload so the servers only send back to your clients, instead of someone else who happened to use the same port as you. (lets say it sends the string Send me your info for XYZ app!
)Send me your info for XYZ app!
and sends the UDP message Name:Server1 IP:192.168.1.2 Port:1234
back to the senders source port and IP combination (192.168.1.4:50123
)Send me your info for XYZ app!
and sends the UDP message Name:Server2 IP:192.168.1.3 Port:4567
message back to the senders source port and IP combination (192.168.1.4:50123
)If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With