How to Close C# Socket Ports

In C#, you can close a listening port by calling the Close() method on the Socket object. Here is an example code:

using System;
using System.Net;
using System.Net.Sockets;

class Program
{
    static void Main()
    {
        // 创建一个Socket对象
        Socket listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

        // 绑定监听端口
        IPEndPoint localEndPoint = new IPEndPoint(IPAddress.Any, 12345);
        listener.Bind(localEndPoint);

        // 开始监听
        listener.Listen(10);
        Console.WriteLine("Listening on port 12345...");

        // 关闭监听端口
        listener.Close();
        Console.WriteLine("Port 12345 closed.");

        Console.ReadLine();
    }
}

In the code above, we first create a Socket object and bind it to port 12345, then call the Close() method to shut down the listening port. After closing the port, the program will print a message saying “Port 12345 closed.”

bannerAds