c# - 实现 C# Tcp 打洞时出错 - 无法在 NAT 后面连接

标签 c# sockets networking nat

我有一个带有公共(public) IP 地址的服务器和一个在 NAT 后面的客户端机器,它们是用 C# 语言实现的。 我尝试编写一个 tcp 打洞程序,但在从服务器到客户端建立套接字时出错。我的步骤如下:

1) 1st,我建立一个到公共(public)服务器的套接字连接并向它发送消息并开始监听端口 17000

2) 2nd, 服务器获取消息并解析它

3) 第三,我在服务器端获得了 remoteEndPoint IpAddress 和端口号 ( =Nat router Ip & Port )

4) 第 4 次尝试连接到套接字 (NAT Ip,Nat Port) 并从服务器在端口 17000 上向客户端发送消息 => 意味着 = 我已经将套接字连接到 nat 路由器并希望路由器将我的消息发送到后面的客户端自然

但是我遇到了以下错误: "连接尝试失败,因为连接方在一段时间后没有正确响应,或者建立连接失败,因为连接的主机未能响应 X.X.X.X: 24352"

谁能帮我解决这个问题。

提前致谢。

最佳答案

你的问题可能出在这里:

and Hope the router send my msg to client behind nat

Nat穿越(如打洞)取决于具体NAT的实现。 您假设由于 NAT 从客户端的端口 17000 看到了一个数据包,并将其映射到某个 NAT 端口 X,那么它会将所有来自端口 X 的数据包转发回客户端。 并非所有 NAT 都这样做!

来自 Microsoft Technet:

The following types of NATs are defined:

  • Cone NATs: A NAT in which the NAT translation table entry stores a mapping between an internal address and port number and an external address and port number. Once the NAT translation table entry is in place, inbound traffic to the external address and port number from any source address and port number is allowed and translated.

  • Restricted NATs: A NAT in which the NAT translation table entry stores a mapping between an internal address and port number and an external address and port number, for either specific source addresses or specific source address and port numbers. An inbound packet that matches the NAT translation table entry for the external destination address and port number from an unknown external address or port number is silently discarded.

  • Symmetric NATs: A NAT that maps the same internal address and port number to different external addresses and ports, depending on the external destination address (for outbound traffic).

您的打洞方法适用于 Cone 和地址受限的 NAT。不适用于对称 NAT 的端口受限 NAT(在您的情况下可能是 NAT)。

关于c# - 实现 C# Tcp 打洞时出错 - 无法在 NAT 后面连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25083683/

相关文章:

linux - 了解虚拟机 IP 地址 ????基本?

c# - 将基类的属性传递给派生类的更好方法?

c# - 使用 C# 代码在运行时将图像按钮图标颜色更改为灰度

java - 服务器上的 AES key 长度错误无效

Java - 仅在本地主机上工作的 UDP 多播

java - 查找以太网连接的网络适配器名称

c# - RichTextBox 选择同一单词的多次出现

c# - ASP.NET MVC 2 Html.TextAreaFor Html.TextArea 奇怪的绑定(bind)

linux - 通过套接字连接发送 GUI/TUI

java - 想要在 openshift 上托管 JAVA 中的原始套接字程序