1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139
|
/*Platform Linux/Ubuntu
ANSI C++11 ISO
This program reads the network and displays active and inactive IPs
*/
#include <cstdlib>
#include <iostream>
#include <cstring>
#include <fstream>
#include <string>
#include <cstdio>
#include <unistd.h>
#include <sys/wait.h>
using namespace std;
int main()
{
//Get the ip addresses from the network and write to file
//system("ifconfig | grep 'inet addr:' | cut -d: -f2 | awk '{print $1}' > ipfile.txt");
system("ifconfig en0 | grep inet | awk '{print $2}' > ~/desktop/ipfile.txt");
string ipaddr="";
ifstream rd;
int ip_range[4]= {192,168,0,1}; //4 octets
//open and read a IP address
/*rd.open("/Users/ashari/desktop/ipfile.txt");
if(rd.is_open()==true)
cout<<"File Opened"<<endl;
else{
cout<<"File open fail"<<endl;
return 0;}
string lineignore;
getline(rd, lineignore);
while(rd>>ipaddr)
{
cout<<"Reading Surrounding Network "<<ipaddr<<endl;
cout<<"Done"<<endl<<endl;
}
rd.close();
//convert string IP to int IP
char* tokens;
char ip[(ipaddr.length())+1];
int i=0;
strcpy(ip, ipaddr.c_str());
tokens= strtok(ip, ".");
while(tokens!=NULL)
{
ip_range[i]=atoi(tokens);
tokens=strtok(NULL,".");
i++;
}*/
//initialise
char ipCmd[100]="p", ipParse[100]="p";
char firstOctet[3], secondOctet[3], thirdOctet[3], fourthOctet[3];
//convert to char
sprintf(firstOctet,"%d",ip_range[0]);
sprintf(secondOctet, "%d",ip_range[1]);
cout<<"index 0 -> "<<ip_range[0]<<endl;
cout<<"first octet "<<firstOctet<<endl;
cout<<"2nd octet "<<secondOctet<<endl;
//loop through the network IPs to check active and inactive IPs
for(int outerOct=1; outerOct<=2; outerOct++)
{
for(int innerOct=1; innerOct<=2; innerOct++)
{
//initialise ping command
char ping[100]="ping -t 3 ";
char success[]="; echo $?";//add at end of the command
//copy IP octets to command
strcpy(ipCmd,firstOctet);
strcat(ipCmd,".");
strcat(ipCmd,secondOctet);
strcat(ipCmd,".");
sprintf(thirdOctet, "%d",outerOct);
strcat(ipCmd,thirdOctet);
strcat(ipCmd,".");
sprintf(fourthOctet, "%d",innerOct);
strcat(ipCmd,fourthOctet);
cout<<"ipCmnd "<<ipCmd<<endl;
//get IP as chars
strcpy(ipParse, firstOctet);
strcat(ipParse,".");
strcat(ipParse,secondOctet);
strcat(ipParse,".");
strcat(ipParse, thirdOctet);
strcat(ipParse,".");
strcat(ipParse, fourthOctet);
cout<<"Checking if "<<ipParse<<" is active or no\n /*If ping return 0 then IP is up else down*/"<<endl<<endl;
cout<<"ping is "<<ping<<endl;
//build command
strcat(ping,ipCmd);
cout<<"ping is "<<ping<<endl;
strcat(ping, success);
system(ping);//execute ping
}
}
return 0;
}
|