ubuntu1804 64bit C语言搜索wifi程序
以下是一份简单的C语言程序,用于在Ubuntu 18.04 64位系统上搜索可用的Wifi网络:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <linux/wireless.h>
#include <net/if.h>
#define WIFI_INTERFACE "wlo1" // 替换为你的无线网卡接口名
int main() {
struct iwreq iw;
int sockfd;
char network_name[32];
// 创建socket并检查是否成功
sockfd = socket(AF_INET, SOCK_DGRAM, 0);
if (sockfd < 0) {
printf("Error creating socket\n");
return -1;
}
// 设置iwreq结构体
memset(&iw, 0, sizeof(iw));
strncpy(iw.ifr_name, WIFI_INTERFACE, IFNAMSIZ);
// 获取Wifi的扫描结果
if (ioctl(sockfd, SIOCSIWSCAN, &iw) < 0) {
printf("Error scanning wifi networks\n");
close(sockfd);
return -1;
}
// 遍历扫描结果并打印网络名称
while (ioctl(sockfd, SIOCGIWSCAN, &iw) == 0) {
struct iw_event iwe;
char *ptr = (char *)&iw.u;
// 遍历扫描结果的每个事件
while (ptr < (char *)&iw.u + iw.u.data.length) {
memcpy(&iwe, ptr, sizeof(iwe));
// 如果扫描到新的网络,则输出其名称
if (iwe.cmd == SIOCGIWAP) {
struct sockaddr *sa = (struct sockaddr *)&iwe.u.ap_addr;
inet_ntop(AF_INET, &sa->sa_data[2], network_name, sizeof(network_name));
printf("Network Name: %s\n", network_name);
}
ptr += iwe.len;
}
usleep(1000);
}
close(sockfd);
return 0;
}
说明:
- 请将WIFI_INTERFACE替换为你的无线网卡接口名,可以使用
ifconfig命令查看。 - 该程序使用了Linux无线扩展库
linux/wireless.h中的函数和结构体,需要在编译时链接该库,使用gcc编译时需要加上-lwifi参数:gcc wifi_search.c -o wifi_search -lwifi。 - 扫描Wifi网络需要root权限,因此需要以sudo权限运行该程序
原文地址: https://www.cveoy.top/t/topic/fiXB 著作权归作者所有。请勿转载和采集!