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
| #include <cstdlib>
#include <iostream>
#define MAX_SIZE 9999
using namespace std;
// Cette fonction retourne l'adresse IP codée
// compréhensible par la base de données.
int formatIp(char *ip)
{
char* ca;
char* cb;
char* cc;
char* cd;
int ipFormated, ia, ib, ic, id;
ca = strtok(ip, ".");
sscanf(ca, "%d", &ia);
cb = strtok(NULL, ".");
sscanf(cb, "%d", &ib);
cc = strtok(NULL, ".");
sscanf(cc, "%d", &ic);
cd = strtok(NULL, ".");
sscanf(cd, "%d", &id);
ia *= (256*256*256);
ib *= (256*256);
ic *= 256;
ipFormated = ia + ib + ic + id;
return ipFormated;
}
// Cette fonction ouvre la base de données pour
// extraire les strings qu'elle contient.
// On effectue ensuite une comparaison avec l'IP codée
// pour savoir si c'est elle qui correspond,
// auquel cas on retourne le nom du pays.
char* database(int ipFormated, FILE *bdd)
{
int ipFrom, ipTo;
char* cIpFrom;
char* cIpTo;
char* countryCode;
char* countryName;
char string[MAX_SIZE] = "";
bdd = fopen("database.txt", "r");
if (bdd != NULL)
{
while (fgets(string, MAX_SIZE, bdd) != NULL) // On lit le fichier tant qu'on ne reçoit pas d'erreur (NULL)
{
cIpFrom = strtok(string, ",");
sscanf(cIpFrom, "%d", &ipFrom);
cIpTo = strtok(string, ",");
sscanf(cIpTo, "%d", &ipTo);
countryCode = strtok(string, ",");
countryName = strtok(string, ",");
if(ipFormated > ipFrom && ipFormated < ipTo)
{
return countryName;
}
}
fclose(bdd);
}
}
// Fonction principale.
int main(int argc, char *argv[])
{
char ip[20];
cout << "Entrez votre adresse IP" << endl;
cin >> ip; // on enregistre l'IP
FILE *bdd = NULL; // pour la base de données.
cout << "Le pays associe a cette adresse est : " << database(formatIp(ip), bdd) << endl; //affichage de la nationalité
system("PAUSE");
return 0;
} |