zoukankan      html  css  js  c++  java
  • C#获取WIFI的连接状态

    C#获取WIFI的连接状态

    本文是在知道WIFI网络设备名称的情况下,获取该设备的连接状态,同样也是可以判断是否已连接广域网

    思路


    1. 起初是想着有没有那样一个直接访问设备信息,通过这个返回的信息来得到我想要的状态,查了一个资料在Linux上有个libiw,这个包能扫描到的ssid的相关信息,并不是我想要的。

    2. 那么只能从另外一个方式入手,首先取得设备的Gateway信息,然后Ping这个Gateway.IPAddress会得到Ping的结果,从这个结果来判断是否连接是否成功。

    问题得到解决


    通过思路2,查找相关的C#方面的资料,果然有相关的API, 通过NetworkInterface这个类来得到所有的网络设备信息,然后再根据条件找出我关注的网络设备,再通过Ping这个类SendPingAsync取得Ping的结果,最后由结果来判别连接状态。

    代码展示


    NetworkInterface[] nfaces = NetworkInterface.GetAllNetworkInterfaces();
    var nface = nfaces.First(x => x.Name == "WLAN 2");
    if (nface == null)
    {
        MessageBox.Show("WLAN2 - Wifi未连接.");
        return;
    }
    var ipProperties = nface.GetIPProperties();
    // 获取默认网关
    var defualtGateway = ipProperties.GatewayAddresses[0];
    Ping ping = new Ping();
    var treplay = ping.SendPingAsync(defualtGateway.Address);
    var replay = treplay.Result;
    MessageBox.Show(replay?.Status == IPStatus.Success
                    ? $"WLAN2 - Wifi已连接. [Ping {defualtGateway.Address} Status: {replay?.Status}]"
                    : $"WLAN2 - Wifi未连接. [Ping {defualtGateway.Address} Status: {replay?.Status}]");
    

    断开与连接WIFI状态效果


    在OrangePI Linux Arm32上的测试效果

    Microsoft (R) Build Engine version 16.7.1+52cd83677 for .NET
    Copyright (C) Microsoft Corporation. All rights reserved.
    
      Determining projects to restore...
      Restored /root/OrangePICallbox/WifiConnection/WifiConnection.csproj (in 1.29 sec).
      WifiConnection -> /root/OrangePICallbox/WifiConnection/bin/Debug/netcoreapp3.1/WifiConnection.dll
    
    Build succeeded.
        0 Warning(s)
        0 Error(s)
    
    Time Elapsed 00:00:18.64
    root@orangepipcplus:~/OrangePICallbox/WifiConnection# dotnet run
    wlan0 - Wifi已连接. [Ping 192.168.31.1 Status: Success]
    root@orangepipcplus:~/OrangePICallbox/WifiConnection#
    
  • 相关阅读:
    为什么要用设计模式?先看看6大原则(一)
    git版本库的创建和yaf框架环境的部署
    laravel日常小问题
    Session store not set on request.
    phpstudy集成环境安装lavarel
    html中提交表单并实现不跳转页面处理返回值
    document load 与document ready的区别
    定时器优化
    放大镜
    子组件调用父组件的方法并传递数据
  • 原文地址:https://www.cnblogs.com/linxmouse/p/14177446.html
Copyright © 2011-2022 走看看