Is there a way in .net 2.0 to discover the network alias for the machine that my code is running on? Specifically, if my workgroup sees my machine as //jekkedev01, how do I retrieve that name programmatically?
Use the System.Environment class. It has a property for retrieving the machine name, which is retrieved from the NetBios. Unless I am misunderstanding your question.
I don't need the local machine name. I need the alias(es) that the domain server has attached to the local machine.
If you need the computer description, it is stored in registry:
- key:
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\lanmanserver\parameters
- value name:
srvcomment
- data type:
REG_SZ (string)
AFAIK it has nothing to do with any domain server, or with the network the PC is attached to.
For anything related to the network, I am using the following:
- NETBIOS name:
System.Environment.MachineName
- host name:
System.Net.Dns.GetHostName()
- DNS name:
System.Net.Dns.GetHostEntry("LocalHost").HostName
If the PC has multiple NETBIOS names, I do not know any other method but to group the names based on the IP address they resolve to, and even this is not reliable if the PC has multiple network interfaces.
I'm not a .NET programmer, but the System.Net.DNS.GetHostEntry method looks like what you need. It returns an instance of the IPHostEntry class which contains the Aliases property.
Since you can have multiple network interfaces, each of which can have multiple IPs, and any single IP can have multiple names that can resolve to it, there may be more than one.
If you want to know all the names by which your DNS server knows your machine, you can loop through them all like this:
public ArrayList GetAllDnsNames() {
ArrayList names = new ArrayList();
IPHostEntry host;
//check each Network Interface
foreach (NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces()) {
//check each IP address claimed by this Network Interface
foreach (UnicastIPAddressInformation i in nic.GetIPProperties().UnicastAddresses) {
//get the DNS host entry for this IP address
host = System.Net.Dns.GetHostEntry(i.Address.ToString());
if (!names.Contains(host.HostName)) {
names.Add(host.HostName);
}
//check each alias, adding each to the list
foreach (string s in host.Aliases) {
if (!names.Contains(s)) {
names.Add(s);
}
}
}
}
//add "simple" host name - above loop returns fully qualified domain names (FQDNs)
//but this method returns just the machine name without domain information
names.Add(System.Net.Dns.GetHostName());
return names;
}