Bonjour,
Je cherche a testé la validité d'une adresse IP en pure C.
- pas de String
- pas de getopt
- pas de strtok
- pas de strstr
- pas de regex
les codes sur internet utilise strtok ou strstr ca ne fonctionne pas, car la string est modifiée
Je suis aller sur internet sur une recherche comment tester une ip.
j'ai fait tout les liens et testé quelques code, ca ne fonctionne pas
je récupère toujours le premier nombre, par exemple si j'ai
192.168.2.4
ca me retourne 192.
les codes suivant ne fonctionnent pas sauf si l'adresse est mise dans un buffer mais pas en tant argument (argv[1]) par exemple.
int validate_ip(const char *ip)
{
int i;
int num;
int dots = 0;
char *ptr;
if (ip == NULL)
return 0;
ptr = strtok(ip, "."); //cut the string using dor delimiter
if (ptr == NULL)
return 0;
while (ptr)
{
if (!validate_number(ptr)) //check whether the sub string is holding only number or not
return 0;
num = atoi(ptr); //convert substring to number
if (num >= 0 && num <= 255)
{
ptr = strtok(NULL, "."); //cut the next part of the string
if (ptr != NULL)
dots++; //increase the dot count
}
else return 0;
}
if (dots != 3) //if the number of dots are not 3, return false
return 0;
return 1;
}
et ce code:
int checkIPType(char* queryIP)
{
/*
This function takes a string queryIP as input and returns "IPv4" if IP is a valid IPv4 address,
"IPv6" if IP is a valid IPv6 address or "Neither" if IP is not a correct IP of any type.
Parameters:
queryIP (char*): The IP address to be checked
Returns:
char*: "IPv4" if IP is a valid IPv4 address, "IPv6" if IP is a valid IPv6 address or "Neither"
if IP is not a correct IP of any type.
*/
// Check if the IP address is IPv4
int count = 0;
char* token = strtok(queryIP, ".");
while (token != NULL)
{
int i;
int num;
int len;
count++;
len = strlen(token);
if (count > 4 || len > 3) {
return 1;
}
for (i = 0; i < len; i++) {
if (!isdigit(token[i])) {
return 1;
}
}
num = atoi(token);
if (num < 0 || num > 255 || (len > 1 && token[0] == '0')) {
return 1;
}
token = strtok(NULL, ".");
}
if (count != 4) {
return 1;
}
return 0;
}
J'ai tenté de modifier le type de paramètre en const char * ou char const char * ca ne donne rien.
Avez vous une idéee ?
Est ce que quelqu'un aurait par hasard fait ce genre de code ?
Merci.