最新做一个WIFI应用项目。如何检测WIFI USB设备是否插上了呢?特此共享。

第一种方法,采用读取文件的方式。在linux下,任何一种设备都可看成文件。通过分析相关文件信息,可得知WIFI设备是否存在;代码示例如下:

static void WIFI_Enum_Device(void)
{
    char  buff[1024];
    FILE * fh;

/* Check if /proc/net/wireless is available */
    fh = fopen(PROC_NET_WIRELESS, "r");

if(fh != NULL)
    {
        /* Success : use data from /proc/net/wireless */

/* Eat 2 lines of header */
        fgets(buff, sizeof(buff), fh);
        fgets(buff, sizeof(buff), fh);

/* Read each device line */
        while(fgets(buff, sizeof(buff), fh))
        {
            char name[IFNAMSIZ + 1];
            char *s;

/* Skip empty or almost empty lines. It seems that in some
            * cases fgets return a line with only a newline. */
            if((buff[0] == '\0') || (buff[1] == '\0'))
                continue;

/* Extract interface name */
            s = WIFI_Get_DeviceName(name, sizeof(name), buff);

if(!s)
            {
            /* Failed to parse, complain and continue */
#ifndef IW_RESTRIC_ENUM
                fprintf(stderr, "Cannot parse " PROC_NET_DEV "\n");
#else
                fprintf(stderr, "Cannot parse " PROC_NET_WIRELESS "\n");
#endif
            }
            else
                /* Got it, save the name about this interface */

{//we always use the first detected device when doing first time detecting
                if(s_DeviceCount == 0)
                {
                    if(strcmp(s_Deviceinfo.DeviceName,name))
                    {
                        memset((char *)&s_Deviceinfo, 0, sizeof(DeviceInfo_t));

memcpy(s_Deviceinfo.DeviceName,name,IFNAMSIZ);
                    }
                    if(strlen(s_SavedDevice) == 0)//this is the first detected device when doing first time detecting, we save it
                        memcpy(s_SavedDevice,name,IFNAMSIZ);
                }
                else
                {//there is more than one device, we should use the first detected
                    if(!strcmp(s_SavedDevice,name))
                    {
                        memset((char *)&s_Deviceinfo, 0, sizeof(DeviceInfo_t));

memcpy(s_Deviceinfo.DeviceName,name,IFNAMSIZ);
                    }
                }
                s_DeviceCount++;
            }
        }

fclose(fh);
    }
   
}

static char* WIFI_Get_DeviceName(char * name, /* Where to store the name */
       int nsize, /* Size of name buffer */
       char * buf) /* Current position in buffer */
{
    char * end;

/* Skip leading spaces */
    while(isspace(*buf))
        buf++;

#ifndef IW_RESTRIC_ENUM
    /* Get name up to the last ':'. Aliases may contain ':' in them,
    * but the last one should be the separator */
    end = strrchr(buf, ':');
#else
    /* Get name up to ": "
    * Note : we compare to ": " to make sure to process aliased interfaces
    * properly. Doesn't work on /proc/net/dev, because it doesn't guarantee
    * a ' ' after the ':'*/
    end = strstr(buf, ": ");
#endif

/* Not found ??? To big ??? */
    if((end == NULL) || (((end - buf) + 1) > nsize))
        return(NULL);

/* Copy */
    memcpy(name, buf, (end - buf));
    name[end - buf] = '\0';

/* Return value currently unused, just make sure it's non-NULL */
    return(end);
}

RETURN_TYPE APP_WIFI_DetectDevice(void)
{
    char command[50] = {'\0'};
    s_DeviceCount = 0;  //reset count
    WIFI_Enum_Device();
    s_LastDeviceCount = s_DeviceCount;
    if(s_DeviceCount > 0)
    {
        sprintf(command,"ifconfig %s up",s_Deviceinfo.DeviceName);
        system(command);  //boot up the device firstly
        return SYS_NOERROR;
    }
    else
        return SYS_FAILED;        
}

第二种方法,利用linux ioctl函数读取I/O接口的相关信息。

/*****************************************************************************
*  Name        : trid_char * APP_NetLink_GetIFFLAGS(char *NetDev )
*  Description : Get net interface IFFLAGS
*  Params      : NetDev
*  Returns     : the string of the NetDev
*  Author/date : Danny.Hu /2011.11.16
*****************************************************************************/
RETURN_TYPE APP_NetLink_GetIFFlags( trid_char *NetDev )
{
    int fd = -1;
    int InterfaceFlags;
    struct ifreq ifr;
    memset(&ifr, 0, sizeof(ifr));
    strcpy(ifr.ifr_name, NetDev);
    fd = socket(AF_INET, SOCK_DGRAM, 0);
    if (fd < 0) 
    {
        printf("Cannot get control socket\n");
        close(fd);
        return SYS_FAILED;
    }
    else if( 0!=(ioctl(fd, SIOCGIFFLAGS, (char*)&ifr)) )
    {
       printf("Cannot get Network Interface Flags!\n");
       close(fd);
       return SYS_FAILED;
    }
    
    InterfaceFlags = ifr.ifr_flags; 
    
    printf("<");
    if ( InterfaceFlags & IFF_UP)                        printf("Network %s is UP, ", NetDev);
    if ( InterfaceFlags & IFF_BROADCAST)     printf("Network %s is BCAST, ", NetDev);
    if ( InterfaceFlags & IFF_MULTICAST)      printf("Network %s is MCAST, ", NetDev);
    if ( InterfaceFlags & IFF_LOOPBACK)       printf("Network %s is LOOP, ", NetDev);
    if ( InterfaceFlags & IFF_POINTOPOINT)   printf("Network %s is P2P, ", NetDev);
    printf(">\n");
    close(fd);
    return  SYS_NOERROR;
}

Linux C程序如何检测WIFI无线USB网卡是否可用?的更多相关文章

  1. TL-WDN5200H无线usb网卡在Linux上的使用

    买了个TL-WDN5200H无线usb网卡,但是发现它居然不支持Linux,但是我有时需要在Linux上使用,这就尴尬了.于是到网上搜索资料,终于解决了这个问题. 首先编译安装:https://git ...

  2. linux,windows下检测指定的IP地址是否可用或者检测IP地址冲突的3种方式(批处理程序,python程序,linux shell 批量ping)

    本文中的脚本适用范围: 1)检测某些IP地址是否被占用: 2)检测网络中某些设备是否存活: 3)在分配新的ip地址之前,批量检测环境中是否存在冲突的机器 以上检测基于ICMP Ping报文,要求所有的 ...

  3. 最近在无线USB网卡投入比较大

    第一次(40): 乐光N18网卡 17 5米USB延长线 10 DVD2 3 运费10 第二次(30): 8187L主板13 5DB/6DB全向天线 5 外壳FREE 运费12 第三次(20): 8D ...

  4. 【智能无线小车系列八】在树莓派上使用USB网卡

    在这个腾“云”驾“物”(云:云计算,物:物联网)的时代,什么都可以没有,就是不能没有网络,树莓派也离不开它.本章节将详细介绍如何将树莓派接入互联网,因为有一些后期将要使用到的小软件需要联网进行下载和安 ...

  5. 基于Orangpi Zero和Linux ALSA实现WIFI无线音箱(二)

    作品已经完成,先上源码: https://files.cnblogs.com/files/qzrzq1/WIFISpeaker.zip 全文包含三篇,这是第二篇,主要讲述发送端程序的原理和过程. 第一 ...

  6. 基于Orangpi Zero和Linux ALSA实现WIFI无线音箱(一)

    作品已经完成,先上源码: https://files.cnblogs.com/files/qzrzq1/WIFISpeaker.zip 全文包含三篇,这是第一篇,作为前言和概述. 第二篇:基于Oran ...

  7. 基于Orangpi Zero和Linux ALSA实现WIFI无线音箱(三)

    作品已经完成,先上源码: https://files.cnblogs.com/files/qzrzq1/WIFISpeaker.zip 全文包含三篇,这是第三篇,主要讲述接收端程序的原理和过程. 第一 ...

  8. 【树莓派】【转】利用USB网卡配置树莓派为无线热点

    由于Wifi很慢,基本不可用:树莓派有无线网卡,恰好看到有文章用树莓派来做无线热点,利用树莓派来共享无线网络.比较有用,转发后续尝试. 本文转自:https://www.embbnux.com/201 ...

  9. 如何在 Arch Linux 的终端里设定 WiFi 网络

    如果你使用的是其他 Linux 发行版 而不是 Arch CLI,那么可能会不习惯在终端里设置 WiFi.尽管整个过程有点简单,不过我还是要讲一下.在这篇文章里,我将带领新手们通过一步步的设置向导,把 ...

随机推荐

  1. Oracle composite index column ordering

    Question:  I have a SQL with multiple columns in my where clause.  I know that Oracle can only choos ...

  2. MSVC CRT运行库启动代码分析

    原文链接:http://www.programlife.net/msvc-crt-startup.html 在程序进入main/WinMain函数之前,需要先进行C运行库的初始化操作,通过在Visua ...

  3. mysql 中 isnull 和 ifnull 判断字段是否为null

    对于统计count(type)和avg(type) 都不起作用 SQL中有ISNULL方法,介绍如下: ISNULL使用指定的替换值替换 NULL. 语法ISNULL ( check_expressi ...

  4. 树状数组的笔记√(hzwer blog)

    int lowbit(int x) { return x&(-x); } lowbit()的返回值就是 2^k 次方的值. 求数组的和的算法: (1)首先,令sum=0,转向第二步: (2)接 ...

  5. [hackerrank]John and GCD list

    https://www.hackerrank.com/contests/w8/challenges/john-and-gcd-list 简单题,GCD和LCM. #include <vector ...

  6. 【mysql的编程专题④】存储过程

    类似函数,但是没有返回值,把sql进行封装,便于多次使用或多种应用程序共享使用.不能用在SQL语句中,只能使用CALL调用; 创建存储过程 语法 CREATE PROCEDURE sp_name ([ ...

  7. 缓存初解(三)---Spring3.0基于注解的缓存配置+Ehcache和OScache

    本文将构建一个普通工程来说明spring注解缓存的使用方式,关于如何在web应用中使用注解缓存,请参见: Spring基于注解的缓存配置--web应用实例 一.简介 在spring的modules包中 ...

  8. flexbox弹性盒子布局

    混合划分 demo1,css: #demo1{ width: 100%; background: #ccc; display: -webkit-flex;/*表示使用弹性布局*/ } #demo1 . ...

  9. JS中用execCommand("SaveAs")保存页面兼容性问题解决方案

    开发环境:ASP.NET MVC,其他环境仅供参考. 问题描述:在开发中遇到这样的需求,保存页面,通常使用JavaScript的saveAs进行保存,各浏览器对saveAs支持,见下表. 代码一:初始 ...

  10. Topcoder 练习小记,Java 与 Python 分别实现。

    Topcoder上的一道题目,题目描述如下: Problem Statement      Byteland is a city with many skyscrapers, so it's a pe ...