SoFunction
Updated on 2025-03-01

C# Obtain geographical information through IP


/// <summary>
/// Get the IP location province and city (Porschev) through IP
      /// </summary>
      /// <param name="ip"></param>
      /// <returns></returns>
      public string GetAdrByIp(string ip)
      {
          string url = "http:///ip/?ip=" + ip;
          string regStr = "(?<=<span\\s*id=\\\"cz_addr\\\">).*?(?=</span>)";
//Get the web page source code
          string html = GetHtml(url);
          Regex reg = new Regex(regStr, );
          Match ma = (html);
          html = ;
          string[] arr = (' ');
          return arr[0];
      }
      /// <summary>
/// Get HTML source code information (Porschev)
      /// </summary>
/// <param name="url">Get address</param>
/// <returns>HTML source code</returns>
      public string GetHtml(string url)
      {
          string str = "";
          try
          {
              Uri uri = new Uri(url);
              WebRequest wr = (uri);
              Stream s = ().GetResponseStream();
              StreamReader sr = new StreamReader(s, );
              str = ();
          }
          catch (Exception e)
          {
          }
          return str;
      }
      /// <summary>
/// Get the real IP and location details (Porschev)
      /// </summary>
      /// <returns></returns>
      public string GetIpDetails()
      {
//Set the URL to obtain the IP address and country source code
          string url = "http:///";
          string regStr = "(?<=<td\\s*align=\\\"center\\\">)[^<]*?(?=<br/><br/></td>)";
//IP Regularity
          string ipRegStr = "((2[0-4]\\d|25[0-5]|[01]?\\d\\d?)\\.){3}(2[0-4]\\d|25[0-5]|[01]?\\d\\d?)";
//IP address
          string ip = ;
//nation
          string country = ;
//Provincial and municipal
          string adr = ;
//Get the web page source code
          string html = GetHtml(url);
          Regex reg = new Regex(regStr, );
          Match ma = (html); html = ;
          Regex ipReg = new Regex(ipRegStr, );
          ma = (html);
//Get IP
          ip = ;
          int index = (":") + 1;
//Get the country
          country = (index);
          adr = GetAdrByIp(ip);
return "IP:" + ip + " Country:" + country + " Province and city:" + adr;
      }