您的位置:首页 > 理论基础 > 计算机网络

检测网络是否连接的两种方法(C#)

2009-03-27 17:49 691 查看

如何去检测网络的连接状态(C#)

1. 方法定义
[DllImport("wininet.dll")]
private extern static bool InternetGetConnectedState( out int connectionDescription, int reservedValue ) ;
2. 方法说明
参数:
connectionDescription : 连接说明
reservedValue : 保留值
返回值:
true: On Line
false: Off Line
3. 调用方法
a. 你必须在你的code里引用System.Runtime.InteropServices,否则,会有编译错误
b. 定义一个变量 int I = 0;
c. 调用bool state = InternetGetConnectedState(out I,0);

完整的代码:
using System.Runtime.InteropServices;
namespace internet
{
public class Class1
{

[DllImport("wininet.dll")]
private extern static bool InternetGetConnectedState( out int connectionDescription, int reservedValue ) ;
public Class1(){}

private bool IsConnected()

{

int I=0;

bool state = InternetGetConnectedState(out I,0);

return state;

}
}
}

ping的函数代码

private void button2_Click(object sender, EventArgs e)
{
System.Net.NetworkInformation.Ping p = new System.Net.NetworkInformation.Ping();
System.Net.NetworkInformation.PingOptions options = new System.Net.NetworkInformation.PingOptions();
options.DontFragment = true;
string data = "abc";
byte[] buffer = Encoding.ASCII.GetBytes(data);
int timeout = 1000;
System.Net.NetworkInformation.PingReply reply = p.Send("www.google.com", timeout, buffer, options);
MessageBox.Show(reply.Status.ToString());
}

返回值:Success 则为通
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: