C# - Get Machine Name / Host Name Program

Learn, how to get and print the machine name / hostname of the computer using C# program?
Submitted by Nidhi, on October 13, 2020 [Last updated : March 22, 2023]

Here, we will find the hostname of the local machine and then print on the console screen.

C# program to get the hostname of the computer

The source code to print the hostname of the computer is given below. The given program is compiled and executed successfully on Microsoft Visual Studio.

//C# - Get Machine Name / Host Name Program.

using System;
using System.Net;

class Network
{
    static void Main()
    {
        string hostName = "";
        hostName = Dns.GetHostName();
        Console.WriteLine("Hostname of computer: " + hostName);
    }
}

Output

Hostname of computer: IncludeHelp-PC
Press any key to continue . . .

Explanation

Here, we created a class Network that contains the Main() method. The Main() method is the entry point for the program.

In the Main() method, we created a string variable hostname then we get the hostname of the local machine using GetHostName() of Dns class. To use Dns class, we need to import System.Net and then print the hostname of the machine on the console screen.

C# Basic Programs »

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.