Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I have a variable containing a URL.

string url;

It may contain loop-back host name. For example, its value could be the following:

http://localhost/x

I want to ensure that the URL will be usable from a different computer that has access to the current computer. If it is a loop-back URL, this won't work.

For example, if the current computer's domain name is webserver.company.local, how can I programmatically replace loop-back URLs' host names this value?

Note that this is for an ASP.NET application, but I'm also interested in a general-purpose solution.

share|improve this question

1 Answer

One approach to this problem is to do the following steps:

  1. Determine if the URL is a loop-back. If so, proceed. One way to do this is using Uri.IsLoopback.
  2. Determine the current computer's DNS host name. This can be done using the static Dns class.
  3. Replace the host name portion of the URL with the current computer's one. This can be done using UriBuilder.

Given this method signature:

Uri MakeExternallyUsable(Uri uri)

Here are two implementations to achieve the desired result:

General Solution

Dns.GetHostName can be used to get the possibly fully-qualified host name. However, I think it would be more robust to use the fully-qualified host name. A mechanism to do this is suggested in this answer.

If you use this approach, make sure to consider the permissions required and the possible exceptions.

if (uri.IsLoopback)
{
    var builder = new UriBuilder(uri)
    {
        Host = Dns.GetHostEntry("LocalHost").HostName
    };

    return builder.Uri;
}
else
    return uri;

ASP.NET

In the context of an ASP.NET response, I think the current computer's host name may not necessarily be the same as the one used by the requester. Also, the computer may have multiple different associated host names. Because of these, getting the host name from the HTTP request's URL seemed suitable to me. Modify the above implementation to use this host name:

/*Get HTTP request*/.Url.Host
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.