Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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)

like image 546
Louis Rhys Avatar asked Feb 24 '12 11:02

Louis Rhys


People also ask

How do I remove my domain name from my computer?

Click "System" in the menu. Within the "System" menu, click "Change Settings." On the "Computer Name" tab, click "Change." Choose "Workgroup" instead of "Domain," and type the name of a new or existing work group. Click "OK," and restart the computer for the changes to take effect.

What is my PC name?

Click on the Start button. In the search box, type Computer. Right click on This PC within the search results and select Properties. Under Computer name, domain, and workgroup settings you will find the computer name listed.

How do I find a computer name from an IP address?

Click the Windows Start button, then "All Programs" and "Accessories." Right-click on "Command Prompt" and choose "Run as Administrator." Type "nslookup %ipaddress%" in the black box that appears on the screen, substituting %ipaddress% with the IP address for which you want to find the hostname.


2 Answers

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).

like image 157
Christian.K Avatar answered Oct 02 '22 16:10

Christian.K


Out of a fqdn:

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

Out of the framework:

System.Net.Dns.GetHostName();
like image 43
StaWho Avatar answered Oct 02 '22 14:10

StaWho