42_ft_nmap/src/main.c
2025-05-29 14:52:09 +02:00

80 lines
1.6 KiB
C

#include <getopt.h>
#include <netinet/in.h>
#include <netinet/tcp.h>
#include <pcap.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "dns.h"
#include "parsing.h"
#include "print.h"
#include "scan.h"
#include "thread.h"
static int scan_host(char *host, const struct option_lst *options)
{
char ip_addr[INET_ADDRSTRLEN];
struct sockaddr_in addr_con;
host[strcspn(host, "\n")] = '\0';
if (dns_lookup(ip_addr, host, &addr_con)) {
dprintf(2,
"ft_nmap: failed to retrieve ip address from "
"'%s'\n",
host);
return 1;
}
struct response responses[1024] = {0};
if (create_threads(options, ip_addr, responses) < 0)
return 1;
return 0;
}
int main(int ac, char **av)
{
if (ac < 2) {
dprintf(2, "Usage: ft_nmap [Scan Type(s)] [Options] {target "
"specification}\n");
print_usage();
return 0;
}
struct option_lst *options = parse_options(ac, av);
if (options == NULL)
return 1;
char *host = get_option_arg(options, FL_IP);
if (host) {
int rv = scan_host(host, options);
free_options(options);
return rv;
}
const char *hosts_path = get_option_arg(options, FL_FILE);
if (!hosts_path) {
dprintf(2, "ft_nmap: address/hostname required\n");
goto error;
}
FILE *hosts_file = fopen(hosts_path, "r");
if (hosts_file == NULL) {
dprintf(2, "ft_nmap: unable to open file '%s'\n", hosts_path);
goto error;
}
char line[256];
while (fgets(line, sizeof(line), hosts_file)) {
if (scan_host(line, options) < 0) {
fclose(hosts_file);
goto error;
}
}
fclose(hosts_file);
free_options(options);
return EXIT_SUCCESS;
error:
free_options(options);
return EXIT_FAILURE;
}