Advertisement
Guest User

Untitled

a guest
Jul 7th, 2019
250
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 8.87 KB | None | 0 0
  1. using System.Collections.Generic;
  2. using System.IO;
  3. using System.Linq;
  4. using System.Net;
  5. using System.Net.Sockets;
  6. using System.Text.RegularExpressions;
  7. using System.Text;
  8. using System.Threading;
  9. using System.Diagnostics;
  10. using System;
  11. using System.Xml;
  12.  
  13. namespace RavelNetworking
  14. {
  15.     static public class Upnp
  16.     {
  17.         static string xmlURL = "";
  18.         static string RouterIP = "";
  19.         static string insertIP ="";
  20.         static string Port = "";
  21.         static string productName = "";
  22.         static bool Gateway;
  23.         static List<string> maplayout;
  24.         static List<string> ServiceTypes = new List<string>();
  25.         static List<string> ControlTypes = new List<string>();
  26.  
  27.         public static void Discover(int port, NetSocket socket)
  28.         {
  29.             insertIP = GetIP();
  30.             Port = port.ToString();
  31.    
  32.             Thread thd = new Thread(Response);
  33.             thd.Start();
  34.         }
  35.  
  36.         static string GetIP()
  37.         {
  38.             var host = Dns.GetHostEntry(Dns.GetHostName());
  39.             foreach (var ip in host.AddressList)
  40.             {
  41.                 if (ip.AddressFamily == AddressFamily.InterNetwork)
  42.                 {
  43.                     return ip.ToString();
  44.                 }
  45.                 throw new Exception("No network adapters with an IPv4 address in the system!");
  46.             }
  47.  
  48.             return "";
  49.         }
  50.  
  51.         static void Response()
  52.         {
  53.             bool finished = false;
  54.  
  55.             Stopwatch sw = new Stopwatch ();
  56.             sw.Start ();
  57.             string[] foundDevices = new string[200];
  58.             int deviceCount = 0;
  59.            
  60.             var ssdpMsg = "M-SEARCH * HTTP/1.1\r\nHOST:239.255.255.250:1900\r\nMAN:\"ssdp:discover\"\r\nST:ssdp:all\r\nMX:5\r\n\r\n";
  61.             var ssdpPacket = Encoding.ASCII.GetBytes(ssdpMsg);
  62.             IPAddress multicastAddress = IPAddress.Parse ("239.255.255.250");
  63.             var socket = new Socket (AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
  64.  
  65.             socket.Bind(new IPEndPoint(IPAddress.Any, 0));
  66.             socket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddMembership, new MulticastOption(multicastAddress, IPAddress.Any));
  67.             socket.SendTo(ssdpPacket,SocketFlags.None, new IPEndPoint(multicastAddress, 1900));
  68.             var response = new byte[8000];
  69.             EndPoint ep = new IPEndPoint(IPAddress.Any, 0);
  70.             socket.Blocking = false;
  71.  
  72.             while (!finished)
  73.             {  
  74.                 try
  75.                 {                  
  76.                     socket.ReceiveFrom(response, ref ep);
  77.                     var str = Encoding.UTF8.GetString(response);
  78.                     var aSTR = str.Split ('\n');
  79.                     foreach (string i in aSTR)
  80.                     {
  81.                        
  82.                         if(i.IndexOf (("SERVER: "),StringComparison.CurrentCultureIgnoreCase) != -1)
  83.                         {
  84.                             string newDev = i.Replace ("Server: ","");
  85.                             if(!foundDevices.Contains (newDev))
  86.                             {
  87.                                 foundDevices[deviceCount] = newDev;
  88.                                 deviceCount++;
  89.                             }
  90.                         }
  91.                        
  92.                         if(i.IndexOf (("LOCATION: "),StringComparison.CurrentCultureIgnoreCase) != -1)
  93.                         {
  94.                             xmlURL = Regex.Replace(i, "Location: ", "", RegexOptions.IgnoreCase);
  95.                             RouterIP = GetBetween (i,"http://","/");
  96.                         }
  97.                        
  98.                         if(i.IndexOf (("InternetGatewayDevice"),StringComparison.CurrentCultureIgnoreCase) != -1)
  99.                         {
  100.                             Gateway = true;
  101.                         }                  
  102.                        
  103.                        
  104.                         if(Gateway)
  105.                         {
  106.                             WebClient webClient = new WebClient();
  107.                             string routerXML = webClient.DownloadString(xmlURL);
  108.  
  109.                             if(routerXML.Contains ("urn:schemas-upnp-org:service:WANIPConnection:0"))
  110.                                 ServiceTypes.Add ("urn:schemas-upnp-org:service:WANIPConnection:0");
  111.  
  112.                             if(routerXML.Contains ("urn:schemas-upnp-org:service:WANIPConnection:1"))
  113.                                 ServiceTypes.Add ("urn:schemas-upnp-org:service:WANIPConnection:1");
  114.  
  115.                             if(routerXML.Contains ("urn:schemas-upnp-org:service:WANPPPConnection:0"))
  116.                                 ServiceTypes.Add ("urn:schemas-upnp-org:service:WANPPPConnection:0");
  117.  
  118.                             if(routerXML.Contains ("urn:schemas-upnp-org:service:WANPPPConnection:1"))
  119.                                 ServiceTypes.Add ("urn:schemas-upnp-org:service:WANPPPConnection:1");
  120.                            
  121.                             if(ServiceTypes.Count == 0)
  122.                             {
  123.                                 socket.Close();
  124.                                 finished = true;
  125.                             }
  126.  
  127.                             foreach(string svcType in ServiceTypes)
  128.                             {
  129.                                 int strIndex = routerXML.IndexOf (svcType);
  130.                                 string ctrlType = GetBetween(routerXML.Substring (strIndex),"<controlURL>","</controlURL>");
  131.                                 ControlTypes.Add (ctrlType);
  132.                             }
  133.  
  134.                             webClient.Dispose ();
  135.                             socket.Shutdown(SocketShutdown.Both);
  136.                             GetMappings();
  137.                             finished = true;
  138.                         }
  139.                     }
  140.                 }catch{}
  141.             }
  142.         }
  143.  
  144.         static void GetMappings()
  145.         {
  146.             for(int s = 0; s < ServiceTypes.Count; s++)
  147.             {
  148.                 maplayout = new List<string> ();
  149.                 string xmlresponse = "";
  150.                 int i = 0;
  151.                 int dex = 0;
  152.                 switch (i)
  153.                 {  
  154.                    
  155.                 case 0:
  156.                     var soapBody =
  157.                         "<s:Envelope xmlns:s=\"http://schemas.xmlsoap.org/soap/envelope/\" s:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\"><s:Body><u:"
  158.                             + "GetGenericPortMappingEntry"
  159.                             + "xmlns:u=\"" + ServiceTypes[s] + "\">"
  160.                             + "<NewPortMappingIndex>"+dex.ToString ()+"</NewPortMappingIndex>"
  161.                             + "<NewRemoteHost></NewRemoteHost>"
  162.                             + "<NewExternalPort></NewExternalPort>"
  163.                             + "<NewProtocol></NewProtocol>"
  164.                             + "<NewInternalPort></NewInternalPort>"
  165.                             + "<NewInternalClient></NewInternalClient>"
  166.                             + "<NewEnabled>1</NewEnabled>"
  167.                             + "<NewPortMappingDescription></NewPortMappingDescription>"
  168.                             + "<NewLeaseDuration></NewLeaseDuration>"
  169.                             + "</u:GetGenericPortMappingEntry></s:Body></s:Body></s:Envelope>\r\n\r\n";
  170.                    
  171.                     byte[] body = System.Text.UTF8Encoding.ASCII.GetBytes (soapBody);
  172.                     var url = "http://" + RouterIP + ControlTypes[s];
  173.                    
  174.                     try
  175.                     {
  176.                         var wr = HttpWebRequest.Create (url);
  177.                         wr.Method = "POST";
  178.                         wr.Headers.Add ("SOAPAction", "\"" + ServiceTypes[s] + "#GetGenericPortMappingEntry" + "\"");
  179.                         wr.ContentType = "text/xml;charset=\"utf-8\"";
  180.                         wr.ContentLength = body.Length;        
  181.                         var stream = wr.GetRequestStream ();
  182.                         stream.Write (body, 0, body.Length);           
  183.                         stream.Flush ();
  184.                         stream.Close ();
  185.                        
  186.                         using (HttpWebResponse response = (HttpWebResponse)wr.GetResponse()) {
  187.                             Stream receiveStream = response.GetResponseStream ();          
  188.                             StreamReader readStream = new StreamReader (receiveStream, Encoding.UTF8);         
  189.                             xmlresponse = readStream.ReadToEnd ();
  190.                             response.Close ();
  191.                             readStream.Close ();
  192.                         }
  193.                     } catch{
  194.                         goto case 2;
  195.                     }          
  196.                     goto case 1;
  197.                    
  198.                 case 1:
  199.                     string thisip = GetBetween (xmlresponse, "<NewInternalClient>", "</NewInternalClient>");
  200.                     string thisport = GetBetween (xmlresponse,"<NewInternalPort>", "</NewInternalPort>");
  201.                     string thisprod = GetBetween (xmlresponse,"<NewPortMappingDescription>","</NewPortMappingDescription>");
  202.                    
  203.                     if(thisip == insertIP && thisprod == productName)                      
  204.                         break;
  205.  
  206.                     dex++;
  207.                     maplayout.Add (thisport);
  208.                     goto case 0;
  209.                    
  210.                 case 2:
  211.                     for(int p = int.Parse (Port); p < ushort.MaxValue;p++)
  212.                     {
  213.                         if(!maplayout.Contains (p.ToString ()))
  214.                         {
  215.                             Port = p.ToString ();
  216.                             SetPort (s);
  217.                             break;
  218.                         }
  219.                     }
  220.                     break;
  221.                 }
  222.             }
  223.         }
  224.        
  225.         static void SetPort(int count)
  226.         {
  227.             string portType = "UDP";
  228.  
  229.             var soapBody =
  230.             "<s:Envelope xmlns:s=\"http://schemas.xmlsoap.org/soap/envelope/\" s:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\"><s:Body><u:"
  231.                     + "AddPortMapping"
  232.                     + " xmlns:u=\"" + ServiceTypes[count] + "\">"
  233.                     + "<NewRemoteHost></NewRemoteHost>"
  234.                     + "<NewExternalPort>" + Port + "</NewExternalPort>"
  235.                     + "<NewProtocol>"+portType+"</NewProtocol>"
  236.                     + "<NewInternalPort>" + Port + "</NewInternalPort>"
  237.                     + "<NewInternalClient>" + insertIP + "</NewInternalClient>"
  238.                     + "<NewEnabled>1</NewEnabled>"
  239.                     + "<NewPortMappingDescription>" + productName + "</NewPortMappingDescription>"
  240.                     + "<NewLeaseDuration>0</NewLeaseDuration>"
  241.                     + "</u:AddPortMapping></s:Body></s:Body></s:Envelope>\r\n\r\n";
  242.            
  243.             byte[] body = System.Text.UTF8Encoding.ASCII.GetBytes(soapBody);
  244.             var url = "http://" + RouterIP+ControlTypes[count];
  245.             var wr = HttpWebRequest.Create(url);
  246.             wr.Method = "POST";
  247.             wr.Headers.Add("SOAPAction","\""+ServiceTypes[count]+"#"+"AddPortMapping"+"\"");
  248.             wr.ContentType = "text/xml;charset=\"utf-8\"";
  249.             wr.ContentLength = body.Length;        
  250.             var stream = wr.GetRequestStream();
  251.             stream.Write(body, 0, body.Length);        
  252.             stream.Flush();
  253.             stream.Close();
  254.         }
  255.  
  256.         static string GetBetween(string strSource, string strStart, string strEnd)
  257.         {
  258.             int Start, End;
  259.             Start = strSource.IndexOf(strStart, 0) + strStart.Length;
  260.             End = strSource.IndexOf(strEnd, Start);
  261.             return strSource.Substring(Start, End - Start);
  262.         }
  263.     }
  264. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement