当前位置: 代码迷 >> .NET相关 >> 求教UDP打洞好手
  详细解决方案

求教UDP打洞好手

热度:8191   发布时间:2013-02-26 00:00:00.0
求教UDP打洞高手
公网Server S能接受到某一公司内网主机E1发来的登陆消息,但是S返回的消息,E1无法接收。是否是公司网关拦截导致的?
代码如下。S端线输入SINIT,然后E1端运行E1Init,然后E1无法接受返回消息。

  static void Main(string[] args)
  {
   
  string serveraddr = "116.233.234.159";
  int port = 8600;
  long e1Addr = 0, e2Addr = 0;
  int e1Port = 0, e2Port = 0;
  System.Net.Sockets.UdpClient u = new System.Net.Sockets.UdpClient(port);
  while (true)
  {
  string cm = Console.ReadLine();
  if (cm == "SINIT")
  {
  while (true)
  {
  System.Net.IPEndPoint ep = new System.Net.IPEndPoint(0, 0);
  byte[] msg = u.Receive(ref ep);
  if (Encoding.ASCII.GetString(msg) == "Hello1")
  {
  e1Addr = ep.Address.Address;
  e1Port = ep.Port;
  for(int i=0;i<1000;i++)
  u.Send(Encoding.ASCII.GetBytes("OK"), 2, ep);
  }
  else if (Encoding.ASCII.GetString(msg) == "Hello2")
  {
  e2Addr = ep.Address.Address;
  e2Port = ep.Port;
  u.Send(Encoding.ASCII.GetBytes("OK"), 2, ep);
  }
  else if (Encoding.ASCII.GetString(msg) == "Need2")
  {
  byte[] t = new byte[sizeof(long) + sizeof(int)];
  Array.Copy(BitConverter.GetBytes(e2Addr), t, sizeof(long));
  Array.Copy(BitConverter.GetBytes(e2Port), 0, t, sizeof(long), sizeof(int));

  u.Send(t, t.Length, ep);
  }
  Console.WriteLine(Encoding.ASCII.GetString(msg));
  System.Threading.Thread.Sleep(100);
  }
  }
  else if (cm == "E1Init")
  {
  System.Net.IPEndPoint ep = new System.Net.IPEndPoint(ConvertToIPValue(serveraddr), port);
  u.Send(Encoding.ASCII.GetBytes("Hello1"), 6, ep);
  byte[] msg = u.Receive(ref ep);
  Console.WriteLine(Encoding.ASCII.GetString(msg));
  }
  else if (cm == "Need2")
  {
  System.Net.IPEndPoint ep = new System.Net.IPEndPoint(ConvertToIPValue(serveraddr), port);
  u.Send(Encoding.ASCII.GetBytes("Need2"), 6, ep);
  byte[] msg = u.Receive(ref ep);
  long addr = BitConverter.ToInt64(msg, 0);
  int e2p = BitConverter.ToInt32(msg, sizeof(long));
  Console.WriteLine(addr + " " + e2p);
  ep = new System.Net.IPEndPoint(addr, e2p);
  u.Send(Encoding.ASCII.GetBytes("Hellop from e1"), "Hellop from e1".Length, ep);
  }
  相关解决方案