I want to know how iwlist command scans the wireless networks available, in linux. I read its source code and there was an ioctl call using SIOCSIWSCAN to trigger the scan and SIOCGIWSCAN to get the scan results. But how the beacon frames are captured and analyzed by these system calls?
iwlist(8) and the other wireless tools provide a common front end to different wireless device drivers that support Linux Wireless Extensions (WEXT). Each driver will register handlers with WEXT that implement the device specific operations defined by this interface. For scanning, the two handlers are trigger scan (command SIOCSIWSCAN) and get scan results (command SIOCGIWSCAN). After the device completes a scan, it sends a SIOCGIWSCAN event to WEXT via a netlink interface. An application listening to this socket can then issue a SIOCGIWSCAN command to get the scan results from the device. Note that the device is free to implement the scan how ever it chooses. For example, it can passively listen for beacons or actively scan by sending out probe requests.
The above is purposely vague on the mechanics of sending commands to a device because there is the traditional way (ioctl) and the new way (netlink - cfg80211). But to take a concrete example, consider the traditional way. The ioctl calls are implemented in the WEXT module but the code that handles this command is implemented in the device driver. When a user space application makes an ioctl, WEXT looks up the device driver's handler and runs it.