Catch the moment when we have a Wi-Fi connection

I need to write a program that performs the following steps:

  • Run the program (daemon)
  • Wait (sleep, block) until Wi-Fi is connected.
  • Send / receive data from the server
  • Wait until the Wi-Fi connection drops.
  • goto 2

The problem is with step 2. I do not know how to catch the moment when a network connection is established. There /proc/net/wireless entryis where information about available wireless connections is displayed, but trying to control it with inotify is not successful. The network connection is established asynchronously.

Here is my test code with inotify (copied mainly from R.Loves book):

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/inotify.h>
#include <sys/select.h>

#define BUF_LEN 1024

int
main() {

    int fd, wd, rc;
    char buf[BUF_LEN];
    ssize_t len, i = 0;
    static fd_set read_fds;

    fd = inotify_init();
    if (fd == -1) {
        perror("inotify_init");
        exit(EXIT_FAILURE);
    }

    wd = inotify_add_watch(fd, "/proc/net/wireless", IN_ALL_EVENTS);
    if (wd == -1) {
        perror("inotify_add_watch");
        exit(EXIT_FAILURE);
    }

    for (;;) {

        FD_ZERO(&read_fds);
        FD_SET(wd, &read_fds);
        rc = select(wd + 1, &read_fds, NULL, NULL, NULL);
        if (rc == -1)
            perror("select");

        len = read(fd, buf, BUF_LEN);
        while (i < len) {
            struct inotify_event *event = (struct inotify_event *) &buf[i];
            printf("wd=%d mask=%d cookie=%d len=%d dir=%s\n",
                event->wd, event->mask, event->cookie, event->len, 
                (event-> mask & IN_ISDIR) ? "yes" : "no");
            if (event->len)
                printf("name=%s\n", event->name);

            i += sizeof(struct inotify_event) + event->len;
        }

        sleep(1);
    }

    return 0;
}

He only catches eternity when I do cat /proc/net/wireless

Question: How to catch the moment when I connected to the network (wifi) using only Linux functions?

P.S. , , .

+3
1

, ( Wi-Fi) netlink, rtnetlink.

, "ip monitor link". , LOWER_UP, , / (EDIT: NO_CARRIER, . Simon).

, , , NetworkManager, ( ) IP- , .

+1

Source: https://habr.com/ru/post/1792182/


All Articles