首页 > 解决方案 > 显示“端口打开/关闭”的程序

问题描述

#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它时,它会因核心转储而崩溃。让我们暂时忽略它。

标签: clinuxport

解决方案


管道命令的退出代码是管道中最后一个命令的退出代码。在您的示例中,这是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
}

推荐阅读