Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

How to reverse a shorten URL to its original link.

0.00/5 (No votes)
13 Jun 2012 2  
An attacker would point to a “harmful” web site or content and you would only see a short URL which would not tell anything about the original URL.

Introduction

This code snippet is useful to get the original URL from a shortened one. This will help its user to check the origin of the URL and will give idea about if you really want to visit that site or not.

Background

URL shorten services are quite popular today. But as a security point of view I always like to know about the origin of the link rather then blindly trusted on the shorted link. This particular codes will help one to check its link without redirecting to the attackers site and yet gives you the original link.

Using the code

This code demonstrates the uses of the simple technique mentioned here. You need a simple website with a Text box, a Label and a button on the Form. When user click on a button it will first check if anything in the TextBox1 and has valid Url by using isValidUrl static method.

If url is valid then it will uses ServerVariables and creates a request and call GetRespose in response object. All we need to at this point is to set a label1.text property with uriString.

string url = TextBox1.Text;
if((TextBox1.Text != "") && (isValidUrl(ref url)))
{
    string userAgent = Request.ServerVariables["HTTP_USER_AGENT"];
    HttpWebRequest request = (HttpWebRequest)(WebRequest.Create(url));
        request.UserAgent = userAgent;
        request.AllowAutoRedirect = false;
    using(HttpWebResponse response = (HttpWebResponse)request.GetResponse())
        {
        // string uriString = response.ResponseUri.AbsoluteUri;
        string uriString = response.Headers["Location"];
                Label1.Text = uriString;
         }
} 
else
{
     Label1.Text = "You have entered Invalid URL. Please enter valid URL in Text box.";
                TextBox1.Focus();
 }   
        

Points of Interest

I have then tested some URLs and the result was as expected, working fine. I guess there is no need to say that I haven’t tested my application with all URL shortening services, so you may find bugs with some other shortening services. If so, please let me know by using the comments section below.

I know some of you might suggest that I should use url validation at the client side by using jQuery or JavaScript. I am interested as well but the point was here to demonstrate "how to reverse a shorten URL" and to that respect I have keep this as simple as possible.

History

Initial Draft saved.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here