参考了网上的一篇文章,由于时间长了,具体地址不知道了。
引入了一个DLL: Interop.NATUPNPLib.dll,实现穿透局域网,进行Socket通信。
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Text.RegularExpressions; using System.IO; using System.Net; using System.Net.Sockets; using NATUPNPLib; namespace _22UPnP穿透内网 { class Program { static void Main(string[] args) { //获取Host Name //------------------------------------------------------------------------- string serverName = Dns.GetHostName(); Console.WriteLine("Server(本机)名称:" + serverName); //从当前Host Name解析IP地址,筛选IPv4地址是本机的内网IP地址。 IPAddress internalIP = Dns.GetHostEntry(serverName).AddressList .Where(i => i.AddressFamily == AddressFamily.InterNetwork) .FirstOrDefault(); Console.WriteLine("Server(本机)内网IP:" + internalIP); UPnPNAT upnp = new UPnPNAT(); IStaticPortMappingCollection staticPortMappingCollection = upnp.StaticPortMappingCollection; if (staticPortMappingCollection == null) { Console.WriteLine("没有检测到路由器,或者路由器不支持UPnP功能。"); return; } int internalPort = 3898;//Server的端口号 int externalPort = 4343;//对应映射的外部端口号 staticPortMappingCollection.Add( externalPort,//外网端口 "TCP",//协议类型 internalPort,//内网端口 internalIP.ToString(),//内网IP地址 true,//是否开启 "UPNP_Test"//描述 ); Socket serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); EndPoint serverEndPoint = new IPEndPoint(internalIP, internalPort); serverSocket.Bind(serverEndPoint); serverSocket.Listen(1); Console.WriteLine("开启服务端监听......\n\n"); Thread serverThread = new Thread(() => { Socket socket = null; while (true) { if (socket!= null || (socket = serverSocket.Accept()) != null) { byte[] byteRec = new byte[1024*1024];//设置消息接收缓存区 int msgLen = socket.Receive(byteRec); string msgRec = Encoding.UTF8.GetString(byteRec,0,msgLen); Console.WriteLine("[Server端]\n收到来自Client的消息:\n{0}", msgRec); } } }); serverThread.IsBackground = true; serverThread.Start(); // 客户端代码段,完整的实现,需将此代码段修改后,在外网的客户端中运行 //------------------------------------------------------------------------- // 获取外网IP地址;方法1 string externalIP;//外网IP变量 externalIP=""; IPAddress[] IPs = Dns.GetHostAddresses("www.baidu.com"); foreach (IPAddress ip in IPs) { Console.WriteLine("获取外网IP成功:" + ip); externalIP = ip.ToString(); } // 方法2 //var regex = @"\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b";//正则 //Console.WriteLine("开始获取外网IP......"); //using (var webclient = new WebClient()) //{ // var rawRes = webclient.DownloadString("https://www.baidu.com/"); // externalIP = Regex.Match(rawRes, regex).Value; //} //externalIP = "111.13.101.208"; // baidu.com //Console.WriteLine("获取外网IP成功:" + externalIP); externalIP = internalIP.ToString(); Thread clientThread = new Thread(() => { ClientConnectToServer(IPAddress.Parse(externalIP), internalPort);//externalPort,在外网运行时,internalPort处需改为externalPort }); clientThread.Start(); Console.ReadKey(); } static void ClientConnectToServer(IPAddress remoteIP, int remotePort) { Socket clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); clientSocket.Connect(new IPEndPoint(remoteIP, remotePort)); IPEndPoint remoteEndPoint = clientSocket.RemoteEndPoint as IPEndPoint; for (int i = 0; i < 3; i++) { string msgFromClient = string.Format("Hello, this msg is from Client. \n{2}\n[Remote IP: {0}, Remote Port: {1} ]\n", remoteEndPoint.Address, remoteEndPoint.Port, DateTime.Now ); byte[] bytes = Encoding.UTF8.GetBytes(msgFromClient); //客户端向服务端发送消息 clientSocket.Send(bytes); Thread.Sleep(1000); } } } }
附:源码下载地址(附有Interop.NATUPNPLib.dll): UPnP_to_through_the_intranet(16-12-8_2324).rar
时间: 2024-10-16 13:08:08