【发布时间】: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