C# TCP Socket 客户端拒绝连接

问题描述 投票:0回答:5

这是我的服务器

在互联网上使用多个不同的端口检查工具时,我在我的服务器上获得连接,证明我的端口已打开

http://www.infobyip.com/tcpportchecker.php

http://www.yougetsignal.com/tools/open-ports/

http://ping.eu/port-chk/

http://ping.eu/port-chk/

static void Main(string[] args)
{
    IPHostEntry ipHostInfo = Dns.Resolve(Dns.GetHostName());
    IPAddress ipAddress = ipHostInfo.AddressList[0];
    IPEndPoint localEndPoint = new IPEndPoint(IPAddress.Any, 10897);
    Console.WriteLine("Server Start");

    Socket listener = new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);
    listener.Bind(localEndPoint);
    listener.Listen(10);
    while (true)
    {
        Console.WriteLine("Waiting for a connection...");
        Socket handler = listener.Accept();
        Console.WriteLine(handler.RemoteEndPoint);
        handler.Shutdown(SocketShutdown.Both);
        handler.Close();
    }
}

这是我的客户代码

 static void Main(string[] args)
 {
     IPEndPoint ip = new IPEndPoint(IPAddress.Parse("MY IP HERE"), 10897);
     Socket server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
     server.Connect(ip);
 }

我每次都会收到此错误,我使用 System.Net.Sockets.TcpClient 和套接字从客户端尝试了多次不同的尝试,并且每次连接被拒绝时,这似乎是我的客户端的问题,因为我的服务器从端口接收连接跳棋

我已经阅读了数十个其他套接字主题,但所有问题都与服务器而不是客户端有关,我不知道出了什么问题有人可以帮助我吗?

编辑: 我可以通过 localhost (127.0.0.1) 连接,但不能从我的公共 IP

c# sockets tcp client connection-refused
5个回答
3
投票

代码运行良好(服务器的前两行不执行任何操作)。您有防火墙或路由问题。


2
投票

问题似乎是我的路由器进行了一些设置,使其不接受到外部 IP 的内部连接,我让我的朋友运行客户端代码,并且连接正常


0
投票

与Windows防火墙异常有关。第一次运行时,您应该会收到允许连接的提示。如果您第一次允许,则会在防火墙中创建例外。也许你否认了。还可以尝试通过 app.manifest 提升应用程序所需的权限


0
投票

我通过在 WiFi 路由器上使用端口转发并在 Windows 防火墙中添加规则来解决这个问题

对于我的 WiFi 上的端口转发,我使用 nugetPackage - OpenNAT 以及下面的代码

static async void UPnP_NAT(int port)
{
try
{
    var discoverer = new NatDiscoverer();
    var cts = new CancellationTokenSource(7000);
    // using SSDP protocol, it discovers NAT device.
    //var device1 = await discoverer.DiscoverDeviceAsync(PortMapper.Pmp, cts);

    var device = await discoverer.DiscoverDeviceAsync(PortMapper.Upnp, cts);

    // display the NAT's IP address
    //Console.WriteLine("The external IP Address is: {0} ", await device.GetExternalIPAsync());
    IPAddress x = await device.GetExternalIPAsync();
    Console.WriteLine("Router's WAN:  " + x.ToString());
    // create a new mapping in the router [external_ip:1702 -> host_machine:1602]
    await device.CreatePortMapAsync(new Mapping(Protocol.Tcp, port, port, "[MY_Server]"));

    foreach (var mapping in await device.GetAllMappingsAsync())
    {
        if (mapping.Description.Contains("[MY_Server]"))
        {
            Console.WriteLine("Mapping on port: xxxxxx" + " - SUCCESSFUL!");
            Console.WriteLine(mapping.ToString());
        }
    }
}
catch (NatDeviceNotFoundException e)
{
    //  Open.NAT wasn't able to find an Upnp device
    Console.WriteLine(e.Message);
}
catch (MappingException me)
{
    switch (me.ErrorCode)
    {
        case 718:
            Console.WriteLine("The external port already in use.");
            break;
        case 728:
            Console.WriteLine("The router's mapping table is full.");
            break;
    }
}
}

为了在 Windows 防火墙中添加规则,我使用了此代码并添加了对 Interop 的引用。 NetFwTypeLib

class SetFirewall
{
private int[] portsSocket = new int[1];
private string[] portsName = new string[1];
private INetFwProfile fwProfile = null;

public SetFirewall(int portsSocket, string portsName)
{
    this.portsSocket[0] = portsSocket;
    this.portsName[0] = portsName;
}

//[PrincipalPermission(SecurityAction.Demand, Role = @"Administrators")]
protected internal void OpenFirewall()
{
    INetFwAuthorizedApplications authApps = null;
    INetFwAuthorizedApplication authApp = null;
    INetFwOpenPorts openPorts = null;
    INetFwOpenPort openPort = null;

    Assembly assembly = Assembly.GetExecutingAssembly();
    string assemblyLocation = assembly.Location.Replace(".dll", ".exe");
    FileVersionInfo fvi = FileVersionInfo.GetVersionInfo(assemblyLocation);
    var companyName = fvi.CompanyName;
    var productName = fvi.ProductName;
    var productVersion = fvi.ProductVersion;
    try
    {
        if (isAppFound(productName) == false)
        {
            SetProfile();
            authApps = fwProfile.AuthorizedApplications;
            authApp = GetInstance("INetAuthApp") as INetFwAuthorizedApplication;
            authApp.Name = productName;
            authApp.ProcessImageFileName = assemblyLocation;
            authApps.Add(authApp);
        }

        for (int i = 0; i < portsSocket.Length; i++)
        {
            if (isPortFound(portsSocket[i]) == false)
            {
                SetProfile();
                openPorts = fwProfile.GloballyOpenPorts;
                openPort = GetInstance("INetOpenPort") as INetFwOpenPort;
                openPort.Port = portsSocket[i];
                openPort.Protocol = NET_FW_IP_PROTOCOL_.NET_FW_IP_PROTOCOL_TCP;
                openPort.Name = portsName[i];
                openPorts.Add(openPort);
            }
        }
    }
    catch (Exception ex)
    {
        //MessageBox.Show(ex.Message);
    }
    finally
    {
        if (authApps != null) authApps = null;
        if (authApp != null) authApp = null;
        if (openPorts != null) openPorts = null;
        if (openPort != null) openPort = null;
    }
}

//[PrincipalPermission(SecurityAction.Demand, Role = @"Administrators")]
protected internal void CloseFirewall()
{
    INetFwAuthorizedApplications apps = null;
    INetFwOpenPorts ports = null;

    Assembly assembly = Assembly.GetExecutingAssembly();
    string assemblyLocation = assembly.Location;
    FileVersionInfo fvi = FileVersionInfo.GetVersionInfo(assemblyLocation);
    var companyName = fvi.CompanyName;
    var productName = fvi.ProductName;
    var productVersion = fvi.ProductVersion;

    try
    {
        if (isAppFound(productName) == true)
        {
            SetProfile();
            apps = fwProfile.AuthorizedApplications;
            apps.Remove(assemblyLocation);
        }

        for (int i = 0; i < portsSocket.Length; i++)
        {
            if (isPortFound(portsSocket[i]) == true)
            {
                SetProfile();
                ports = fwProfile.GloballyOpenPorts;
                ports.Remove(portsSocket[i], NET_FW_IP_PROTOCOL_.NET_FW_IP_PROTOCOL_TCP);
            }
        }
    }
    catch (Exception ex)
    {
        //MessageBox.Show(ex.Message);
    }
    finally
    {
        if (apps != null) apps = null;
        if (ports != null) ports = null;
    }
}

protected internal bool isAppFound(string appName)
{
    bool boolResult = false;
    Type progID = null;
    INetFwMgr firewall = null;
    INetFwAuthorizedApplications apps = null;
    INetFwAuthorizedApplication app = null;
    try
    {
        progID = Type.GetTypeFromProgID("HNetCfg.FwMgr");
        firewall = Activator.CreateInstance(progID) as INetFwMgr;
        if (firewall.LocalPolicy.CurrentProfile.FirewallEnabled)
        {
            apps = firewall.LocalPolicy.CurrentProfile.AuthorizedApplications;
            IEnumerator appEnumerate = apps.GetEnumerator();
            while ((appEnumerate.MoveNext()))
            {
                app = appEnumerate.Current as INetFwAuthorizedApplication;
                if (app.Name == appName)
                {
                    boolResult = true;
                    break;
                }
            }
        }
    }
    catch (Exception ex)
    {
        //MessageBox.Show(ex.Message);
    }
    finally
    {
        if (progID != null) progID = null;
        if (firewall != null) firewall = null;
        if (apps != null) apps = null;
        if (app != null) app = null;
    }
    return boolResult;
}

protected internal bool isPortFound(int portNumber)
{
    bool boolResult = false;
    INetFwOpenPorts ports = null;
    Type progID = null;
    INetFwMgr firewall = null;
    INetFwOpenPort currentPort = null;
    try
    {
        progID = Type.GetTypeFromProgID("HNetCfg.FwMgr");
        firewall = Activator.CreateInstance(progID) as INetFwMgr;
        ports = firewall.LocalPolicy.CurrentProfile.GloballyOpenPorts;
        IEnumerator portEnumerate = ports.GetEnumerator();
        while ((portEnumerate.MoveNext()))
        {
            currentPort = portEnumerate.Current as INetFwOpenPort;
            if (currentPort.Port == portNumber)
            {
                boolResult = true;
                break;
            }
        }
    }
    catch (Exception ex)
    {
        //MessageBox.Show(ex.Message);
    }
    finally
    {
        if (ports != null) ports = null;
        if (progID != null) progID = null;
        if (firewall != null) firewall = null;
        if (currentPort != null) currentPort = null;
    }
    return boolResult;
}

protected internal void SetProfile()
{
    INetFwMgr fwMgr = null;
    INetFwPolicy fwPolicy = null;
    try
    {
        fwMgr = GetInstance("INetFwMgr") as INetFwMgr;
        fwPolicy = fwMgr.LocalPolicy;
        fwProfile = fwPolicy.CurrentProfile;
    }
    catch (Exception ex)
    {
        //MessageBox.Show(ex.Message);
    }
    finally
    {
        if (fwMgr != null) fwMgr = null;
        if (fwPolicy != null) fwPolicy = null;
    }
}

protected internal object GetInstance(string typeName)
{
    Type tpResult = null;
    switch (typeName)
    {
        case "INetFwMgr":
            tpResult = Type.GetTypeFromCLSID(new Guid("{304CE942-6E39-40D8-943A-B913C40C9CD4}"));
            return Activator.CreateInstance(tpResult);
        case "INetAuthApp":
            tpResult = Type.GetTypeFromCLSID(new Guid("{EC9846B3-2762-4A6B-A214-6ACB603462D2}"));
            return Activator.CreateInstance(tpResult);
        case "INetOpenPort":
            tpResult = Type.GetTypeFromCLSID(new Guid("{0CA545C6-37AD-4A6C-BF92-9F7610067EF5}"));
            return Activator.CreateInstance(tpResult);
        default:
            return null;
    }
}
}

-1
投票

这似乎是端口转发/路由问题。使用端口检查器

检查转发的端口是否可访问
© www.soinside.com 2019 - 2024. All rights reserved.