简体   繁体   English

C#套接字,如何获取所有侦听(套接字)计算机的IP地址和端口号

[英]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). 我正在使用C#套接字在设备(客户端)和计算机(服务器)之间建立连接。 All is working good except 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. 除了我要避免用户输入要在设备上连接的IP地址和端口号的事实以外,其他所有程序都工作正常。 Instead I want a listbox or drop down list of all IP addresses with listening sockets. 相反,我需要带有侦听套接字的所有IP地址的列表框或下拉列表。 Just wondering if there's a way to get all the IP addresses and port numbers of hosts with listening (socket)? 只是想知道是否有一种方法可以通过侦听(套接字)获取主机的所有IP地址和端口号?

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. 它基本上涉及测试范围和每个端口中的每个IP地址,并报告该尝试的成功。 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. 例如,这就是某些对等网络在Windows中的工作方式。 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. 通过使用UDP广播,可以将数据发送到正在固定端口监听的服务器。 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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM