C# program to print the IP address of the computer

Here, we are going to learn how to print the IP address of the computer in C#?
Submitted by Nidhi, on October 13, 2020

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

Program:

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

using System;
using System.Net;

class Network
{
    static void Main()
    {
        IPAddress[] ips     ;
        IPHostEntry entry   ;
        string hostName = "";

        hostName = Dns.GetHostName();
        Console.WriteLine("Hostname of computer: " + hostName);

        entry= Dns.GetHostEntry(hostName);
        ips = entry.AddressList;

        for (int i = 0; i < ips.Length; i++)
        {
            Console.WriteLine("IP Address: "+ips[i]);
        }
    }
}

Output:

Hostname of computer: IncludeHelp-PC
IP Address: 192.168.10.25
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.

Here, we got the IP address of the local machine based on hostname using GetHostEntry() method and AddressList property then printed the IP address on the console screen, as we know that one machine can have multiple IP addresses for different networks like TCP/IP, Wifi, and GPRS.






Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.





Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates


© https://www.includehelp.com some rights reserved.