ubuntu1804 搜索wifi的C程序
以下是一个简单的C程序,可以在Ubuntu 18.04上搜索可用的WiFi网络:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <errno.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <net/if.h>
#include <sys/ioctl.h>
#include <linux/wireless.h>
int main() {
int sockfd;
struct iwreq req;
char buffer[1024];
sockfd = socket(AF_INET, SOCK_DGRAM, 0);
if(sockfd < 0) {
perror("Socket error");
return 1;
}
strncpy(req.ifr_name, "wlan0", IFNAMSIZ);
if(ioctl(sockfd, SIOCGIWNAME, &req) == -1) {
perror("Wireless interface not found");
close(sockfd);
return 1;
}
if(ioctl(sockfd, SIOCGIWSCAN, &req) == -1) {
perror("Scan failed");
close(sockfd);
return 1;
}
struct iw_scan_req scan_req;
memset(&scan_req, 0, sizeof(scan_req));
strncpy(scan_req.ifname, "wlan0", IFNAMSIZ);
scan_req.scan_type = IW_SCAN_TYPE_PASSIVE;
scan_req.scan_flags = 0;
req.u.data.pointer = (caddr_t) &scan_req;
req.u.data.length = sizeof(scan_req);
req.u.data.flags = 0;
if(ioctl(sockfd, SIOCSIWSCAN, &req) == -1) {
perror("Scan request failed");
close(sockfd);
return 1;
}
sleep(5);
req.u.data.pointer = buffer;
req.u.data.length = sizeof(buffer);
req.u.data.flags = 0;
if(ioctl(sockfd, SIOCGIWSCAN, &req) == -1) {
perror("Failed to get scan results");
close(sockfd);
return 1;
}
struct iw_event iwe;
struct iw_scan_ap_info ap_info;
char ssid[IW_ESSID_MAX_SIZE + 1];
memcpy(&iwe, buffer, sizeof(iwe));
while(iwe.cmd != SIOCGIWSCAN) {
if(iwe.cmd == SIOCGIWAP) {
memcpy(&ap_info, &iwe.u.ap_info, sizeof(ap_info));
} else if(iwe.cmd == SIOCGIWFREQ) {
printf("SSID: %s\n", ssid);
printf("Frequency: %d MHz\n", iwe.u.freq.m);
} else if(iwe.cmd == SIOCGIWESSID) {
memcpy(ssid, iwe.u.essid.pointer, iwe.u.essid.length);
ssid[iwe.u.essid.length] = '\0';
}
memcpy(&iwe, ((char *) &iwe) + iwe.len, sizeof(iwe));
}
close(sockfd);
return 0;
}
请注意,此程序需要在root权限下运行
原文地址: https://www.cveoy.top/t/topic/fiXs 著作权归作者所有。请勿转载和采集!