提供一個C#獲取本機IP地址的方法,不會出現獲取的ip地址是IPV6或不能用的

// 嘗試Ping指定IP是否能夠Ping通
public static bool IsPingIP(string strIP)
{
try
{
//創建Ping對象
Ping ping = new Ping();
//接受Ping返回值
PingReply reply = ping.Send(strIP, 1000);
//Ping通
return true;
}
catch
{
//Ping失敗
return false;
}
}
//得到網關地址
public static string GetGateway()
{
//網關地址
string strGateway = "";
//獲取所有網卡
NetworkInterface[] nics = NetworkInterface.GetAllNetworkInterfaces();
//遍歷數組
foreach (var netWork in nics)
{
//單個網卡的IP對象
IPInterfaceProperties ip = netWork.GetIPProperties();
//獲取該IP對象的網關
GatewayIPAddressInformationCollection gateways = ip.GatewayAddresses;
foreach (var gateWay in gateways)
{
//如果能夠Ping通網關
if (IsPingIP(gateWay.Address.ToString()))
{
//得到網關地址
strGateway = gateWay.Address.ToString();
//跳出循環
break;
}
}
//如果已經得到網關地址
if (strGateway.Length > 0)
{
//跳出循環
break;
}
}
//返回網關地址
return strGateway;
}
//得到IP地址
public static string GetIp()
{
string IPname = "";
try
{
string name = Dns.GetHostName();
IPAddress[] ips;
ips = Dns.GetHostAddresses(name);

string temp = GetGateway();
string gateway = string.Empty;
int num = 0;
for (int i = 0; i < temp.Length; i++)
{
if (temp.Substring(i, 1) == ".")
{
num += 1;
if (num == 3)
i = temp.Length;
}
if (num != 3)
gateway += temp.Substring(i, 1);
}
for (int i = 0; i < ips.Length; i++)
{
if (ips[i].ToString().StartsWith(gateway))
{
IPname += ips[i];
i = ips.Length;
}
}
}
catch
{ }
return IPname;
}

用法

textBox1.Text = GetIp();
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章