private static IPAddress GetExternalIPAddress(string serviceUrl) { string RequestText = "<?xml version=\"1.0\"?>" + "<s:Envelope xmlns:s=\"http://schemas.xmlsoap.org/soap/envelope/\" s:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\">" + "<s:Body>" + "<u:GetExternalIPAddress xmlns:u=\"urn:schemas-upnp-org:service:WAN" + (_WANPPP ? "PPP" : "IP") + "Connection:1\"></u:GetExternalIPAddress>" + "</s:Body>" + "</s:Envelope>"; byte[] RequestBytes = Encoding.ASCII.GetBytes(RequestText); // Request the router tell us the external ip byte[] ResponseBytes = null; string ResponseText = null; using (RMWebClient WC = new RMWebClient()) { WC.ContentType = "text/xml; charset=\"utf-8\""; WC.Headers.Add("SOAPACTION", "\"urn:schemas-upnp-org:service:WAN" + (_WANPPP ? "PPP" : "IP") + "Connection:1#GetExternalIPAddress\""); WC.Timeout = 5000; ResponseBytes = WC.UploadData(serviceUrl, RequestBytes); ResponseText = Encoding.ASCII.GetString(ResponseBytes); } // Load xml into parser XmlDocument XmlDoc = new XmlDocument(); XmlDoc.LoadXml(ResponseText); // Add namespace XmlNamespaceManager NSManager = new XmlNamespaceManager(XmlDoc.NameTable); NSManager.AddNamespace("tns", "urn:schemas-upnp-org:device-1-0"); // Get IP string IP = XmlDoc.SelectSingleNode("//NewExternalIPAddress/text()", NSManager).Value; // Return if it's valid IPAddress Result = null; if (IPAddress.TryParse(IP, out Result) && !WebUtils.IsPrivateIP(Result)) { return(Result); } else { return(IPAddress.None); } }
public static IPAddress GetExternalIPv4ByHttp(int port) { using (RMWebClient WC = new RMWebClient()) { WC.Timeout = 5000; string IP = WC.DownloadString("http://www.randm.ca:" + port.ToString() + "/whats-my-ip.php"); // Return if it's valid IPAddress Result = IPAddress.None; if (IPAddress.TryParse(IP, out Result) && !WebUtils.IsPrivateIP(Result)) { return(Result); } } return(IPAddress.None); }
private static IPAddress GetPublicAddressResponse(List <UdpClient> clients) { // Loop through that list of clients up to 100 times to check for a discovery response IPEndPoint RemoteEndPoint = null; for (int i = 0; i < 100; i++) { foreach (UdpClient Client in clients) { try { // Check if this client has a response if (Client.Available > 0) { byte[] ResponseBytes = Client.Receive(ref RemoteEndPoint); if ((ResponseBytes.Length == 12) && (ResponseBytes[0] == 0) && (ResponseBytes[1] == 128) && (IPAddress.NetworkToHostOrder(BitConverter.ToInt16(ResponseBytes, 2)) == 0)) { IPAddress Result = new IPAddress(new byte[] { ResponseBytes[8], ResponseBytes[9], ResponseBytes[10], ResponseBytes[11] }); if (!WebUtils.IsPrivateIP(Result)) { return(Result); } } } } catch { // Ignore } } // 100 times through at 50 millisecond sleep each time means we'll wait up to 5 seconds for a response Thread.Sleep(50); } return(IPAddress.None); }