This article mainly introduces the C # detection port is occupied by a simple example, the need for friends can refer to when we want to create a TCP/IP Server connection, we need a range of 1000 to 65535 ports. But a port on this machine can only be monitored by one program, so we need to detect if the port is occupied when we listen locally. Namespace System.Net.NetworkInformation defines a class called ipglobalproperties, which we use to get all the listening connections and then determine if the port is occupied, as follows: Code as follows: public static bool Portinuse (int port) { bool InUse = false; Ipglobalproper Ties ipproperties = Ipglobalproperties.getipglobalproperties (); ipendpoint[] ipendpoints = Ipproperties.getactivetcplisteners (); foreach (IPEndPoint endPoint in ipendpoints) { if (endPoint . Port = port) { InUse = true; & nbsp break; } { return inUse; We use the Httplistner class to start a listener on port 8080 and then test if it can be detected, the code is as follows: code is as follows: static void Main (string[)args) { HttpListener Httplistner = new HttpListener (); HTTPLISTNER.PREFIXES.ADD ("http://*:808 0/"); Httplistner.start (); Console.WriteLine ("port:8080 Status:" + (Portinuse (8080)?) In use ': ' Not in use '); Console.readkey (); Httplistner.close (); }
The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion;
products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the
content of the page makes you feel confusing, please write us an email, we will handle the problem
within 5 days after receiving your email.
If you find any instances of plagiarism from the community, please send an email to:
info-contact@alibabacloud.com
and provide relevant evidence. A staff member will contact you within 5 working days.