Scan the entire Internet looking for webservers

This revision is from 2024/02/10 06:10. You can Restore it.

#include 
#include 
#include 
#include 
#include 
#include 
#include 

#define PORT_80 80
#define PORT_443 443

char *check_port_open(int port, char *ip_address) {
    int sock = socket(AF_INET, SOCK_STREAM, 0);
    if (sock == -1) {
        perror("Failed to create socket");
        return NULL;
    }

    struct sockaddr_in server_addr;
    memset(&server_addr, 0, sizeof(server_addr));
    server_addr.sin_family = AF_INET;
    server_addr.sin_port = htons(port);
    inet_pton(AF_INET, ip_address, &server_addr.sin_addr);

    int result = connect(sock, (struct sockaddr *)&server_addr, sizeof(server_addr));
    close(sock);

    if (result == 0) {
        printf("Port %d is open on %sn", port, ip_address);
        return strdup(ip_address); // Allocate memory for the copied IP address
    } else {
        if (errno != ECONNREFUSED && errno != ENETUNREACH) {
            perror("Failed to connect");
        }
        return NULL;
    }
}

int main() {
    char *subnet = "192.168.1.";
    FILE *csv_file = fopen("open_ports.csv", "w");
    if (csv_file == NULL) {
        perror("Failed to open CSV file");
        return 1;
    }

    for (int i = 1; i <= 255; ++i) {
        char ip_address[16];
        snprintf(ip_address, 16, "%s%d", subnet, i);

        char *open_ip = check_port_open(PORT_80, ip_address);
        if (open_ip != NULL) {
            fprintf(csv_file, "%s,%dn", open_ip, PORT_80);
            free(open_ip);
        }

        open_ip = check_port_open(PORT_443, ip_address);
        if (open_ip != NULL) {
            fprintf(csv_file, "%s,%dn", open_ip, PORT_443);
            free(open_ip);
        }
    }

    fclose(csv_file);
    return 0;
}

  

📝 📜 ⏱️ ⬆️