How to get a simple computer name (without the domain name) out of a full computer name in c#?

StackOverflow https://stackoverflow.com/questions/9429992

  •  12-11-2019
  •  | 
  •  

Question

Can I get just a simple computer name (without the domain name) from a fully qualified name (can be with or without a domain name)? Is it possible for a computer name to have a dot (.) sign in it?

(this question seems to be doing the reverse)

Was it helpful?

Solution

No hostnames cannot contain a dot (reference Wikipedia and RFC 952 (see "ASSUMPTIONS") and RFC 1123). It is the delimiter between the hostname and the domainname. So you can simply do

string fullName = "foobar.domain";
string hostName = fullName.Substring(0, fullName.IndexOf('.'));

(With proper error checking of course, for the case that "fullName" is not actually a fullname).

OTHER TIPS

Out of a fqdn:

string s = "some.computer.name";
string host = s.Substring(0, s.IndexOf('.'));

Out of the framework:

System.Net.Dns.GetHostName();
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top