开发者

C# Sockets, How to get IP addresses and port # of all listening (sockets) computers

I am using C# sockets to have a connection between a device (client) and a computer (server). All is working good e开发者_如何学Pythonxcept for the fact that I am trying to avoid the user to enter the IP address and port number wherein to connect to on the device. Instead I want a listbox or drop down list of all IP addresses with listening sockets. Just wondering if there's a way to get all the IP addresses and port numbers of hosts with listening (socket)?

Thanks for any help! :)


What you're asking to do is called a port scan. It basically involves testing each IP address in a range and each port and reporting the success of that attempt. It's slow and it will cause a lot of alarms if there is any kind of threat monitoring on the network because port scanning is one of the ways attackers try to find network vulnerabilities.

So in short, this is a bad idea and probably won't be responsive enough for you to use for this purpose. Instead what you might consider is using a central server as a "directory" that each server would register with.

Or you can send out a broadcast on your subnet and wait for servers to respond. This is how some of the peer networking works in Windows for example. Note that this assumes you are the developer of the server as well and you can add in the logic necessary for the server to listen for broadcasts.


By using UDP broadcast, you can send out the data to the Server which are listening at the fixed port. The following is the working example.

 foreach (IPAddress ip in allLocalNetworkAddresses.AddressList)
        {
            Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);


            //Allow sending broadcast messages
            client.SetSocketOption(SocketOptionLevel.Socket,
            SocketOptionName.Broadcast, 1);

               //Create endpoint, broadcast.
            IPEndPoint AllEndPoint = new IPEndPoint(IPAddress.Broadcast, Port);                     

            byte[] sendData = Encoding.ASCII.GetBytes("1");
           //Send message to everyone on this network
            client.SendTo(sendData, AllEndPoint);
            Console.Write("Client send '1' to " + AllEndPoint.ToString() +
            Environment.NewLine);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜