udp hole punching(1)

这两天一直在弄UDP打洞,弄得晕头转向的。下面说说我对UDP打洞的一点理解,希望大家指点!
目标:实现两个只有内网IP地址的直接通信(不需要经过服务器的中转)
关键字:
1。NAT(网络地址解析):内网的主机向公网的服务器发送数据时,路由会利用NAT机制将内网的地址解析成公网的地址。
2。Session(会话):一个会话是由内部IpEndPoint和目的公网IpEndPoint组成的,在第一个udp包被发送出去的时候创建.
如下:如果client想向server发送一个udp数据包,在server看来client是Nath后的IpEndPoint:221.65.14.32:4000,这时Session记录了192.168.0.10:7000和60.65.54.41:5000
这样在server向221.65.14.32:4000发送数据时Nat会利用Session将数据发送到192.168.0.10:7000

------------| client |----------| Nat |-------------| server |
------------192.168.0.10:7000--------->221.65.14.32:4000------------>60.65.54.41:5000
实现udp打洞:
前提:在一段时间内,内部主机利用相同的端口向不同服务器发送UDP数据包时Nat端会分配相同的端口
也 就是说利用192.168.0.10:7000依次向server1:60.65.54.41:5000和server2:60.65.54.41: 5200发送udp数据包时,从server1和server2来看client的地址都是221.65.14.32:4000。
Server端代码:
 UdpClient firstUdp  =   new  UdpClient( 7100 );
UdpClient secondUdp 
=   new  UdpClient( 7200 );
 IPEndPoint  remote
= new  IPEndPoint(IPAddress.Any, 0 );
 
while  ( true )
{
    firstUdp.Receive(
ref remote);
    Console.WriteLine(
"First Udp Packet Come From:{0}",remote.ToString());
     secondUdp.Receive(
ref remote);
      Console.WriteLine(
"First Udp Packet Come From:{0}",remote.ToString());
       Console.WriteLine(
"===========================");

}
Client端代码:
// client,use one udpclient send each udp server a udp packet
using  System;
using  System.Collections.Generic;
using  System.Text;
using  System.Net;
using  System.Net.Sockets;

namespace  UdpTestClient
{
class Program
{
static void Main(string[] args)
{
IPAddress addr 
=IPAddress.Parse("221.198.110.220");
UdpClient client 
= new UdpClient();
byte[] bytes=System.Text.Encoding.ASCII.GetBytes("fasdf");
client.Send(bytes,bytes.Length,
new IPEndPoint(addr,7100));
Console.WriteLine(
"Just Wait five seconds...");
System.Threading.Thread.Sleep(
5000);
client.Send(bytes, bytes.Length, 
new IPEndPoint(addr, 7200));
}

}

}
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值