John
John

Reputation: 65

Reading Data from File into Array - C

I'm doing a project on Kali Linux where I run the tool Ettercap that lists IP addresses on a network and saves them to a .txt. I then need to use these IP's on another tool nmap, so I wanted to write a C code that can save the IPs from IP.txt into an array. So far this is the closest working code:

#include <stdio.h>
#include <stdlib.h>

main(){

    FILE *ipList;
    ipList = fopen("IP.txt", "r");

    int ipArray[10];
    int i;

    if (ipList == NULL)
    {
        printf("Error\n");
        exit (0);
    }
    for (i = 0; i < 10; i++)
    {
        fscanf(ipList, "%d,", &ipArray[i] );

    }

    for (i = 0; i < 10; i++)
    {
           printf("nmap -A -T4 -F %d\n\n", ipArray[i]);
        }

    fclose(ipList);

    return 0;
}

The resulting output is just a bunch of random numbers. Any ideas? Does it matter that I'm using Kali? And my ipArray is set to 10; will it be a problem if I don't have 10 ip addresses?


The IP addresses are stored like this:

IP address : 10.0.0.1

IP address : 10.0.0.2

IP address : 10.0.0.3

IP address : 10.0.0.4


I've made progress. This is my current out put:

nmap -A -T4 -F IP|nnmap -A -T4 -F address|nnmap -A -T4 -F :|nnmap -A -T4 -F 10.0.2.2|nnmap -A -T4 -F IP|nnmap -A -T4 -F address|nnmap -A -T4 -F :|nnmap -A -T4 -F 10.0.2.3|nnmap -A -T4 -F IP|nnmap -A -T4 -F address|nnmap -A -T4 -F :|nnmap -A -T4 -F 10.0.2.4

Here is my current code:

#include <stdio.h>

#include <stdlib.h>



main() {



FILE *ipList;
ipList = fopen("IP.txt","r");



char ip_addr[256];



while (fscanf(ipList, "%255s", ip_addr) == 1){

printf("nmap -A -T4 -F %s|n", ip_addr);

}



if (ipList == NULL){

printf("error\n");

exit (1);

}



fclose(ipList);

return 0;

}

So now my goal is to have the code ignore "IP address :" and if possible output it as a list.

Upvotes: 2

Views: 1252

Answers (1)

Jonathan Leffler
Jonathan Leffler

Reputation: 753645

Given that the input format is lines such as:

IP address : 10.0.0.1

then you need to read the address as a string, or as 4 separate small integers.

char *ip_address[16];

for (i = 0; i < 10; i++)
{
    if (fscanf(fp, "IP address : %15s", ip_address) != 1)
        …report format error…
    …code to convert dotted-decimal to IPv4 address…
}

or:

int ip[4];

for (i = 0; i < 10; i++)
{
    if (fscanf(fp, "IP address : %d.%d.%d.%d", &ip[0], &ip[1], &ip[2], &ip[3]) != 4)
        …report format error…
    for (j = 0; j < 4; j++)
    {
        if (ip[j] < 0 || ip[j] > 255)
            …report bogus value…
    }
    …convert dotted-decimal values into IPv4 address…
}

Upvotes: 1

Related Questions