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

本文介绍了一种使用C#检测网络连接状态的方法,通过调用wininet.dll中的InternetGetConnectedState函数来判断设备是否在线,并提供了一个简单的示例程序。此外,还提供了使用Ping类检查特定网站连通性的代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

如何去检测网络的连接状态(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 则为通

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值