Linux环境下新手如何用C程序调用nmap获取局域网连接设备信息
在C程序中调用nmap并收集局域网设备扫描结果
作为Linux下的网络编程新手,你可以通过C语言的popen()函数调用nmap命令并捕获输出,再将结果存入动态扩容的字符串数组(模拟字符串向量)中。以下是具体实现方案:
核心思路
- 用
popen()启动nmap命令并创建管道,读取命令的标准输出 - 逐行读取输出内容,存入动态扩容的字符串数组
- 遍历数组打印结果,最后释放所有资源
完整代码示例
#include <stdio.h> #include <stdlib.h> #include <string.h> #define INITIAL_CAPACITY 8 #define BUFFER_SIZE 256 int main() { // 初始化动态字符串数组 char** results = malloc(INITIAL_CAPACITY * sizeof(char*)); if (!results) { perror("内存分配失败"); return 1; } int capacity = INITIAL_CAPACITY; int count = 0; // 调用nmap命令,打开管道读取输出 FILE* pipe = popen("nmap -sn 192.168.1.1/24", "r"); if (!pipe) { perror("执行nmap命令失败"); free(results); return 1; } char buffer[BUFFER_SIZE]; // 逐行读取输出内容 while (fgets(buffer, BUFFER_SIZE, pipe) != NULL) { // 去除换行符 buffer[strcspn(buffer, "\n")] = '\0'; // 数组容量不足时自动扩容 if (count >= capacity) { capacity *= 2; char** temp = realloc(results, capacity * sizeof(char*)); if (!temp) { perror("内存扩容失败"); // 清理已分配的内存 for (int i = 0; i < count; i++) { free(results[i]); } free(results); pclose(pipe); return 1; } results = temp; } // 复制当前行到数组 results[count] = malloc(strlen(buffer) + 1); if (!results[count]) { perror("行内存分配失败"); // 清理资源 for (int i = 0; i < count; i++) { free(results[i]); } free(results); pclose(pipe); return 1; } strcpy(results[count], buffer); count++; } // 关闭管道 int status = pclose(pipe); if (status == -1) { perror("管道关闭失败"); } // 打印所有扫描结果 printf("扫描到的设备信息:\n"); for (int i = 0; i < count; i++) { printf("- %s\n", results[i]); free(results[i]); } free(results); return 0; }
注意事项
- 运行程序需要sudo权限,否则nmap可能无法获取完整的设备信息
- 编译命令:
gcc nmap_scan.c -o nmap_scan,执行命令:sudo ./nmap_scan - 代码实现了动态数组自动扩容,同时做了完整的内存释放处理,避免内存泄漏
内容的提问来源于stack exchange,提问作者DirtyV
相关产品推荐
相关产品推荐

