HiveBrain v1.2.0
Get Started
← Back to all entries
patterncsharpMinor

Resolve (domainless) machine name from DNS alias

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
resolvenamednsmachinefromaliasdomainless

Problem

So I have a URI with a DNS alias, and I need to dynamically replace the alias with the actual machine. I started out with this:

var builder = new UriBuilder("http://server-alias/path/to/resource");
builder.Host = Dns.GetHostEntry(builder.Host).HostName;
return builder.Uri; // http://server1.mydomain.net/path/to/resource


However, what I need is the URI with just the machine name, http://server1/path/to/resource. Of course I can use this, but string manipulation seems seems a bit kludgey:

builder.Host = Dns.GetHostEntry(builder.Host).HostName.Split(new[] { '.' }, 2)[0];


Is there a better way to get just the machine name from a DNS alias, without the domain?

Solution

However, what I need is the URI with just the machine name, http://server1/path/to/resource. Of course I can use this, but string manipulation seems seems a bit kludgey:

builder.Host = Dns.GetHostEntry(builder.Host).HostName.Split(new[] { '.' }, 2)[0];


Also this seems to be a little bit strange, I don't know another way, only a cleaner way.

private Uri GetUriFromAlias(String alias)
{
    UriBuilder builder = new UriBuilder(alias);
    IPHostEntry entry = Dns.GetHostEntry(builder.Host);

    builder.Host = GetMachineName(entry);
    return builder.Uri;
}
private String GetMachineName(IPHostEntry entry)
{
    return entry.HostName.Split(new[] { '.' }, 2)[0];
}

Code Snippets

builder.Host = Dns.GetHostEntry(builder.Host).HostName.Split(new[] { '.' }, 2)[0];
private Uri GetUriFromAlias(String alias)
{
    UriBuilder builder = new UriBuilder(alias);
    IPHostEntry entry = Dns.GetHostEntry(builder.Host);

    builder.Host = GetMachineName(entry);
    return builder.Uri;
}
private String GetMachineName(IPHostEntry entry)
{
    return entry.HostName.Split(new[] { '.' }, 2)[0];
}

Context

StackExchange Code Review Q#56673, answer score: 2

Revisions (0)

No revisions yet.