【问题标题】:Open TCP port using UDP?使用UDP打开TCP端口?
【发布时间】:2014-03-13 18:18:08
【问题描述】:

我读过一些关于使用 UDP 打开端口的文章。我找不到我阅读的原始页面,但我确实找到了这个 SO 答案 https://stackoverflow.com/a/1539394

我尝试运行此代码。也许我做错了什么?这个想法(在上面的链接中)是 Alice 侦听端口 5412,将 UDP 数据包从 5412(tcp 端口)发送到 bob 到 5411。 Bob(不听)使用 TCP 端口 5411(udp 端口​​)连接到Alice 5412。我在 bob 上使用命令行给 alice 的 IP 地址。

我做错了吗?当我使用我的公共 IP 地址(和我的网络地址,但不是 127.0.0.1)在本地运行时,我得到了异常 A socket operation was attempted to an unreachable network。当我在 Bob 上运行它时,我得到一个连接超时异常。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;
using System.Net;
using System.Threading;
namespace TcpTest
{
    class Program
    {
        static string localIp = "127.0.0.1";
        static string remoteIP = ipaddr;
        static void Main(string[] args)
        {
            //run remotely to connect to you using TCP
            if (args.Count() > 0)
            {
                var t = new TcpClient(new IPEndPoint(IPAddress.Parse(localIp), 5411)); //Force port
                t.Connect(args[0], 5412);
                return;
            }
            //Run locally
            //Bind TCP port
            var l = new TcpListener(5412);
            l.Start();

            //Send UDP using the listening port to remote address/port
            var u = new UdpClient(5412);
            u.Connect(remoteIP, 5411);
            var buf = new byte[10];
            u.Send(buf, buf.Length);

            //R
            new Thread(SimulateRemote).Start();

            //L
            var c = l.AcceptTcpClient();
            var af=c.Client.RemoteEndPoint;
        }
        static void SimulateRemote()
        {
            Thread.Sleep(500);
            var t = new TcpClient(new IPEndPoint(IPAddress.Parse(localIp), 5411)); //Force port
            t.Connect(myipaddr, 5412);
        }
    }
}

【问题讨论】:

  • UDP 流量从 UDP 端口发送到 UDP 端口。 TCP 流量从 TCP 端口发送到 TCP 端口。没有例外(根据协议规范)。诸如路由器之类的设备可能能够将 TCP 流量与 UDP 相互转换,但这样做并不常见,因为 TCP 基本上是 UDP + 更多数据。如果使用 TCP 的额外开销,丢弃数据几乎没有什么好处。 TCP 端口号的范围是 0 到 65535,UDP 端口号的范围是 0 到 65535。UDP 端口 5411 和 TCP 端口 5411 是两个不同的端口,尽管它们的编号相同。

标签: c# sockets tcp udp firewall


【解决方案1】:

你不能这样做。

TCP 端口和 UDP 端口无法相互连接。您从UdpClient.Send() 发送的数据包将Protocol 字段设置为0x11(UDP 的值),但TCP 堆栈仅识别Protocol 设置为0x06(TCP 的值)的数据包。它是 IP 模块最基本操作的一部分。如果您想了解详细信息,请参阅RFC 791

【讨论】:

  • 听起来不错,但我看到至少有两个帖子说我可以做到。当我使用 UDP 进行连接时,不连接但让防火墙通过 TCP 连接。有什么想法可以通过防火墙/路由器戳一个洞吗?
  • @acidzombie24 帖子有误,或者您误解了它们。对 UDP 连接执行此操作很常见。 TCP 不同。并且任何防火墙都会识别并分离 TCP 和 UDP 端口空间。
  • 我链接的 SO 答案恰好有 this link,上面写着“令人惊讶的是,打孔也适用于 TCP。在传出 SYN 数据包之后,防火墙/NAT 路由器将转发具有合适 IP 地址的传入数据包,并且即使它们未能确认或确认错误的序列号 (ACK),也可以将端口连接到 LAN。”第一页讲述了我使用的步骤。
  • 带有 SYN 的 TCP 数据包和 UDP 数据包之间有很大的区别。没有防火墙会将它们误认为彼此。
  • 所以链接是完全错误的?那种烂。继承人希望那里有 TCP 打孔
猜你喜欢
  • 2013-01-23
  • 2018-12-29
  • 2016-06-06
  • 2021-01-23
  • 2012-02-12
  • 1970-01-01
  • 2011-08-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多