Программа C# для поиска IP-адреса машины

Опубликовано: 12 Сентября, 2022

IP-адрес известен как адрес интернет-протокола. Это уникальный адрес, который идентифицирует устройство в сети. Это почти как набор правил, которые управляют данными, отправляемыми через Интернет или через локальную сеть. Это помогает Интернету различать маршрутизаторы, компьютеры, веб-сайты и т. д. В этой статье мы узнаем, как найти IP-адрес машины с помощью C#.

Использование метода GetHostByName()

Мы можем найти IP-адрес машины, используя метод GetHostByName(). Этот метод возвращает информацию DNS для заданного имени хоста DNS. Когда вы передаете пустую строку в этот метод, он возвращает стандартное имя хоста локального компьютера.

Синтаксис:

public static System.Net.IPHostEntry GetHostByName (string hName);

Здесь hName — DNS-имя хоста.

Подход:

To find the IP address of the machine follow the following steps:

  • Firstly include System.Net.
  • We need to find the name of host to get the IP Address of host. So, the name of host can be retrieved by using the GetHostName() method from the Dns class.
  • By passing the hostname to GetHostByName() method we will get the IP Address.
  • This method returns a structure of type hostent for the specified host name.
  • AddressList[0] gives the ip address and ToString() method is used to convert it to string.

Пример:

C#




// C# program to print the IP address of the machine
using System;  
using System.Text;  
using System.Net;
  
class GFG{
      
static void Main(string[] args)  
{
      
    // Get the Name of HOST  
    string hostName = Dns.GetHostName(); 
    Console.WriteLine(hostName);  
      
    // Get the IP from GetHostByName method of dns class.
    string IP = Dns.GetHostByName(hostName).AddressList[0].ToString();  
    Console.WriteLine("IP Address is : " + IP);  
}  
}

Выход:

IP Address is : 192.168.122.136

Использование метода GetHostEntry()

Мы также можем найти IP-адрес машины с помощью метода GetHostEntry(). Этот метод запрашивает DNS-сервер и возвращает IP-адрес экземпляру IPHostEntry.

Синтаксис:

public static System.Net.IPHostEntry GetHostEntry (IPAddress address);

Подход:

To find the IP address of the machine follow the following steps:

  • Firstly include System.Net.
  • We need to find the name of the host to get the IP Address of the host. So, the name of the host can be retrieved by using the GetHostName method from the DNS class.
  • Bypassing the hostname to GetHostEntry( ) method we will get the IP Address.
  • This method returns a structure of type hostent for the specified hostname.
  • AddressList[0] gives the IP address and the ToString() method is used to convert it to string.

Пример:

C#




// C# program to print the IP address of the machine
using System;  
using System.Text;  
using System.Net;
  
class GFG{
      
static void Main() 
{
    
    // Getting host name
    string host = Dns.GetHostName();
      
    // Getting ip address using host name
    IPHostEntry ip = Dns.GetHostEntry(host);
    Console.WriteLine(ip.AddressList[0].ToString());
}
}

Выход:

IP Address is : 192.168.122.136