一、初識獲取本機ip
在許多網路應用程序中,獲取本機的IP地址是一個關鍵任務。通過C#,我們可以方便地獲取本地系統IP地址。
首先我們需要在C#中引入System.Net命名空間。然後,使用Dns類的GetHostName方法獲取主機名,最後使用GetHostEntry方法返回相應IP地址。
using System.Net;
IPHostEntry hostname = Dns.GetHostEntry(Dns.GetHostName());
foreach (IPAddress ip in hostname.AddressList)
{
Console.WriteLine(ip);
}
二、獲取多個本機ip地址
如果本機有多個網卡或子網,我們需要獲取所有的IP地址以便做出決策。可以通過枚舉網路介面來完成。
首先,引入System.Net.NetworkInformation命名空間。然後,通過NetworkInterface類的GetIPProperties方法獲取IP地址和網關信息。最後,獲取IPv4地址列表。
using System.Net.NetworkInformation;
IPGlobalProperties properties = IPGlobalProperties.GetIPGlobalProperties();
NetworkInterface[] interfaces = NetworkInterface.GetAllNetworkInterfaces();
foreach (NetworkInterface adapter in interfaces)
{
IPInterfaceProperties adapterProperties = adapter.GetIPProperties();
foreach (UnicastIPAddressInformation address in adapterProperties.UnicastAddresses)
{
if (address.Address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
{
Console.WriteLine(address.Address);
}
}
}
三、獲取特定類型的本機ip地址
有時候我們只需要特定類型的IP地址,例如私有IP地址、公共IP地址、IPv4地址等。
要獲取私有IP地址(如192.168.x.x或10.x.x.x),我們可以使用以下代碼:
using System.Net;
using System.Net.NetworkInformation;
foreach (NetworkInterface ni in NetworkInterface.GetAllNetworkInterfaces())
{
IPInterfaceProperties properties = ni.GetIPProperties();
foreach (IPAddressInformation unicast in properties.UnicastAddresses)
{
if (unicast.Address.AddressFamily == AddressFamily.InterNetwork && IPAddress.IsPrivate(unicast.Address))
{
Console.WriteLine(unicast.Address);
}
}
}
要獲取公共IP地址,我們可以使用以下代碼:
using System.Net;
using System.Net.Sockets;
IPHostEntry host = Dns.GetHostEntry(Dns.GetHostName());
foreach (IPAddress ip in host.AddressList)
{
if (ip.AddressFamily == AddressFamily.InterNetwork)
{
if (!IPAddress.IsPrivate(ip))
{
Console.WriteLine(ip);
}
}
}
要獲取IPv4地址,我們可以使用以下代碼:
using System.Net;
using System.Net.NetworkInformation;
foreach (NetworkInterface ni in NetworkInterface.GetAllNetworkInterfaces())
{
IPInterfaceProperties properties = ni.GetIPProperties();
foreach (IPAddressInformation unicast in properties.UnicastAddresses)
{
if (unicast.Address.AddressFamily == AddressFamily.InterNetwork)
{
Console.WriteLine(unicast.Address);
}
}
}
四、總結
在本文中,我們學習了在C#中獲取本機IP地址的多種方法,包括獲取主機名、獲取多個IP地址、獲取特定類型的IP地址。希望這些示例代碼能夠幫助您解決與本地IP地址相關的問題。
原創文章,作者:TDJIN,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/334518.html
微信掃一掃
支付寶掃一掃