C# UPnP로 인트라넷 통과

5073 단어 C#
인터넷의 한 문장을 참고했는데 시간이 길어서 구체적인 주소를 모르겠다.
DLL: Interop 도입NATUPNPLib.dll, 랜을 뚫고 Socket 통신을 합니다.
 
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;
using NATUPNPLib;
using System.Threading;
using System.Text.RegularExpressions;
using System.IO;

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("       ......
"); 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(" Client :
{0}", msgRec); } } }); serverThread.IsBackground = true; serverThread.Start(); // IP string externalIP; // 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("http://checkip.dyndns.org/"); externalIP = Regex.Match(rawRes, regex).Value; } Console.WriteLine(" IP :" + externalIP); Thread clientThread = new Thread(() => { ClientConnectToServer(IPAddress.Parse(externalIP), 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.
{2}
[Remote IP: {0}, Remote Port: {1} ]
", remoteEndPoint.Address, remoteEndPoint.Port, DateTime.Now ); byte[] bytes = Encoding.UTF8.GetBytes(msgFromClient); // clientSocket.Send(bytes); Thread.Sleep(1000); } } } }

첨부: 소스 다운로드 주소: http://download.csdn.net/detail/frombegintoend/5688855
Interop.NATUPNPLib.dll

좋은 웹페이지 즐겨찾기