c - For 循环未被执行 C

标签 c

我正在尝试扫描所有打开的端口并保存文本文件中的端口。该程序显示第一个循环(检查参数是否正确)但出于某种原因跳过整个 for 循环。我是 c 语言的新手,非常感谢任何帮助

#include <stdio.h>
#include <netdb.h>
#include <unistd.h>
#include <string.h>
#include <assert.h>
#include <stdlib.h>

#define HTTP_PORT 80

int main(int argc, char ** argv)
{
    int sockfd=0;
    int min = atoi(argv[1]);
    int max = atoi(argv[2]);
    struct sockaddr_in serv_addr;
    struct hostent *url;

    for(int i = 0; i < argc; i++)
    {
        printf("%d, is %s\n",i,argv[i]);
    }

    sockfd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
    if (sockfd < 0) {
        fprintf(stderr, "ERROR: Failed to open socket\n");
        return 1;
    }

    url = gethostbyname(argv[3]); /* does not support IP6 */
    if (url == NULL) {
        fprintf(stderr, "ERROR: Host not found\n");
        return 2;
    }

    printf("Scanning ports %d - %d\n",  min, max);

    FILE * file = fopen("/home/llp2/Desktop/Assignment/ports.txt", "w");//open log file

    for (unsigned short port = min; port < max; port++)//loop through and scan all ports
    {
            memset(&serv_addr, 0, sizeof(serv_addr));
            serv_addr.sin_family = AF_INET;
            memcpy(&serv_addr.sin_addr, url->h_addr, url->h_length);
            serv_addr.sin_port = htons(HTTP_PORT);

        /* Connect to the server */
        if (connect(sockfd, (struct sockaddr*) &serv_addr, sizeof(serv_addr)) > 0) 
        {   
                //if the port is open get information about that port and print it to the log file
                char host[128];
                char service[128];
                getnameinfo((struct sockaddr*)&serv_addr, sizeof serv_addr, host, (sizeof host), service, sizeof service, 0);
                printf("Port : %d, Service : %s, Open\n", port, service);
                fprintf(file, "Port : %d, Service : %s, Open\n", port, service);
        }

        close(sockfd);
    }

        fclose(file);//Close the file

    return 0;
}

最佳答案

当我按如下方式运行您的代码时,您正在因段错误而崩溃:

g++ code.cpp
./a.out 1000 2000 localhost

对于初学者来说,您将在 for 循环的每次迭代中关闭套接字。当您尝试第二次关闭它时,您可能会得到未定义的结果:

这一行:

    close(sockfd);
}

我怀疑您想在循环的每次迭代中创建一个新套接字。

此外,如果文件无法打开,fclose(file) 调用也会崩溃。

这一行:

fclose(file);//Close the file

应该是这样的:

if (file)
{
    fclose(file);
    file = NULL;
}

关于c - For 循环未被执行 C,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47932674/

相关文章:

c - 字符串转换时 strtol 结果不匹配

c++ - 是否有 WinAPI 可以从带有可选空格和其他参数的命令行获取文件名?

c - C链表遍历中移除条目并释放桶节点时出错

c - 在C中创建字符串矩阵

c - 如何重建给定的 malloc 序列?

c - 有没有不支持任何形式的反射的主要编程语言?

c - srand(getpid()) 会影响格式/结构吗?

c - 将代码移到 main() 之外时出现段错误

c - 为每个 mpi 进程使用不同的 View 写入文件

C程序复利与单利