C#验证网络状态

C#验证网络状态


2024年3月16日发(作者:)

首先引入命名空间:

using pServices;

再定义如下:

[DllImport("")]

private extern static bool InternetGetConnectedState(out int

connectionDescription, int reservedValue);

定义一个判断网络连接的函数:

private bool IsConnected()

{

int I = 0;

bool state = InternetGetConnectedState(out I, 0);

return state;

}

在按钮里写以下代码:

if (IsConnected())

{

("状态:网络畅通!");

}

else

{

("状态:与目标网络无连接!");

}

判断网络状态是否通路有两种情况,一种是电脑有没有接入到网络,另一种是与某一

目标主机之间是否通路。判断是否连入网络可以使用;而判断与某一目标主

机是否通路时暂时想到的就只有ping命令了。

1.判断网络通路:

view plaincopy to clipboardprint?

[DllImport("")]

private extern static bool InternetGetConnectedState(out int

connectionDescription, int reservedValue);

private bool isConnected()

{

int I = 0;

bool state = InternetGetConnectedState(out I, 0);

return state;

}

[DllImport("")]

private extern static bool InternetGetConnectedState(out int

connectionDescription, int reservedValue);

private bool isConnected()

{

int I = 0;

bool state = InternetGetConnectedState(out I, 0);

return state;

}

判断isConnected就可以了

2.判断与某目标主机是否通路:

view plaincopy to clipboardprint?

private static string CmdPing(string strIp)

{

Process p = new Process();

me = ""; //设置程序名

llExecute = false; //关闭shell的使用

ctStandardInput = true; //重定向标准输入

ctStandardOutput = true; //重定向标准输出

ctStandardError = true; //重定向错误输出

NoWindow = true; //不显示窗口

string pingrst;

();

ine("ping -n 1 " + strIp); //-n 1 : 向目标IP发送一

次请求

ine("exit");

string strRst = End(); //命令执行完后返回结果的

所有信息

if(f("(0% loss)") != -1)

{

pingrst = "与目标通路";

}

else if(f("Destination host unreachable.") != -1)

{

pingrst = "无法到达目的主机";

}

else if(f("Request timed out.") != -1)

{

pingrst = "超时";

}

else if(f("not find") != -1)

{

pingrst = "无法解析主机";

}

else

{

pingrst = strRst;

}

();

return pingrst;

}


发布者:admin,转转请注明出处:http://www.yc00.com/news/1710519429a1770951.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信