C#程序查找机器的IP地址
IP 地址称为 Internet 协议地址。它是通过网络识别设备的唯一地址。它几乎就像一组规则,用于管理通过 Internet 或通过本地网络发送的数据。它有助于 Internet 区分路由器、计算机、网站等。在本文中,我们将学习如何使用 C# 查找机器的 IP 地址。
使用 GetHostByName() 方法
我们可以使用 GetHostByName() 方法找到机器的 IP 地址。此方法返回给定 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);
}
}
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
使用 GetHostEntry() 方法
我们还可以使用 GetHostEntry() 方法找到机器的 IP 地址。该方法查询 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