XtremeDocumentStudio
.NET
PDFOne
.NET
XtremeDocumentStudio
(for Java)
PDFOne
(for Java)
XtremeDocumentStudio
Delphi
eDocEngine
VCL
PDFtoolkit
VCL
StarDocs
Web APIs

Gnostice Blog

Tuesday, June 16, 2015

How to reverse lookup an IP address using C#

C# code for a reverse lookup ASP.NET handler.

By V. Subhash

Recently, I had to enhance the IP addresses of this site's log files with reverse DNS names.

A reverse DNS name is a human-friendly name for an IP address (usually represented as a combination of octals). For example, when the BingBot spider hits a site, the remote IP might be logged as 157.55.39.169. A reverse lookup for this address would reveal it as msnbot-157-55-39-169.search.msn.com .

For the lookup, I created an ASP.NET handler. It would get the IP from the URL and respond with just the reverse DNS name. I then the URL of this handler in a JavaScript script in the log files to perform asynchronous reverse lookups. Here is the code for the reverse lookup handler.

<%@ WebHandler Language="C#" Class="ReverseLookup" %>

using System;
using System.Web;
using System.Net;
using System.Net.Sockets;

public class ReverseLookup : IHttpHandler {

  public void ProcessRequest (HttpContext context) {
    if (context.Request.QueryString["ip"] == null) {
      context.Response.Write("Invalid IP");
      return;
    }

    String sIP = context.Request.QueryString["ip"].Trim();

    context.Response.ContentType = "text/plain";
    if (sIP.Length > 0) {
      try {
        IPAddress oIPA = IPAddress.Parse(sIP);
        IPHostEntry oHostEntry = Dns.GetHostEntry(oIPA);
        context.Response.Write(oHostEntry.HostName);
      } catch (SocketException err) {
        context.Response.Write(
          "<a href=\"http://www.bing.com/search?q=" + sIP + "\">" + sIP + "</a>");
      } catch (System.FormatException err) {
        context.Response.Write(sIP + " :-(");
      }
    } else {
      context.Response.Write("Invalid IP");
    }

  }

  public bool IsReusable {
    get {
      return false;
    }
  }
}

Not all IPs have a reverse DNS name. In my original script, I have linked the IP to a IP lookup service that does more than the search engine given above. It even places the IP on a map.

Privacy | Legal | Feedback | Newsletter | Blog | Resellers © 2002-2018 Gnostice Information Technologies Private Limited. All rights reserved.