在C#中,可以使用Socket类来验证IP和端口是否可以通。下面是一个简单的示例代码:

using System;
using System.Net.Sockets;

class Program
{
    static void Main(string[] args)
    {
        string ip = "127.0.0.1";
        int port = 8080;

        if (IsPortOpen(ip, port))
        {
            Console.WriteLine("IP and port are open.");
        }
        else
        {
            Console.WriteLine("IP and port are not open.");
        }
    }

    static bool IsPortOpen(string ip, int port)
    {
        try
        {
            using (TcpClient tcpClient = new TcpClient())
            {
                tcpClient.Connect(ip, port);
                return true;
            }
        }
        catch (Exception)
        {
            return false;
        }
    }
}

在上面的示例代码中,我们使用TcpClient类来尝试连接到指定的IP和端口。如果连接成功,则表示IP和端口是通的;如果连接失败,则表示IP和端口不通

c# 如何验证ip端口是否可以通

原文地址: https://www.cveoy.top/t/topic/hDzQ 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录