提供一个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();
发布了37 篇原创文章 · 获赞 30 · 访问量 8万+

猜你喜欢

转载自blog.csdn.net/sunyiming537/article/details/52484685