c - 显示“端口打开/关闭”的程序
问题描述
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
char command[100];
char portrange[100];
printf("Enter portrange (e.g.,20-30)");
scanf("%s", portrange);
int i=0, range1, range2;
sscanf(portrange, "%d-%d", &range1, &range2);
for(i=range1;i<=range2;i++)
{
sprintf(command, "netstat -aont | grep \"`hostname -i`:%d \" ", i);
printf("command= %d \n", command); //printing the command for testing purpose only
system(command);
//here
//here
printf("%d\n",i);
}
return 0;
}
该程序过滤掉来自netstat -aont |的行。grep " hostname -i
:%d "其中%d被输入的端口范围连续替换。
我想添加一个 if 语句来显示“port#%d is open”如果端口 %d 如果命令成功则打开,或者如果命令失败则显示“port#%d is closed”。如何在for循环中实现这一点?
注意:我在端口范围检查%d
的循环内使用。for
我知道这是错误的,但是当我使用%s
它时,它会因核心转储而崩溃。让我们暂时忽略它。
解决方案
管道命令的退出代码是管道中最后一个命令的退出代码。在您的示例中,这是grep
. 如果grep
成功,它以值 0 退出,否则它不同于 0。
system()返回作为参数传递的命令行的状态。因此,您需要将状态存储在一个变量中:
int status;
...
status = system(...);
您需要使用WIFEXIT() 和 WEXITSTATUS()检查状态的内容。后一个宏将从状态中提取退出代码:
if (WIFEXITED(status)) {
int exit_code = WEXITSTATUS(status);
printf("Exit code is %d\n", exit_code);
// If exit_code is 0 ==> The grep succeeded
}
推荐阅读
- javascript - 尝试使用 MERN 上传图像时出现 400 错误请求错误
- java - 无法检查 Java 调试器 VScode 中的值
- azure - 每个函数 hosts.json 设置而不是全局
- arrays - 角度模板数组插值
- git - 是否有 git 全局配置来显示克隆进度
- javascript - 我是否使用钩子或状态管理将特定对象传递给我的子组件?
- javascript - 使用来自 Google Apps 脚本的过滤器显示表格数据
- c# - 在位图上绘制几何图形 (Avalonia)
- python - Python:尝试在处理错误声明的 else 语句中打印先前定义的变量时出现 NameError
- html - 如何使它从左到右而不是上下对齐