Hello and thank you for taking your time to expalin me some things
So I didn't write this program, I found it online so I would like to know some things a bit more.
This is a program that tests if you have given an IPv4 (ip address) or not...
Code:
#include <stdio.h>
#define QUAD 4 /* if you need a constant define one (or more) */
#define MAXC 17 /* don't skimp on buffer size */
int main (void)
{
char buf[MAXC] = "", /* buf to hold IP read by fgets */
nl = 0; /* charater to validate newline following IP */
int ip[QUAD] = {0}; /* array to store each quad for testing */
printf ("Enter IP address (x.x.x.x): ");
fgets (buf, MAXC, stdin); /* read IP into buf */
if (sscanf (buf, "%d.%d.%d.%d%c", /* parse with sscanf */
&ip[0], &ip[1], &ip[2], &ip[3], &nl) != 5) {
fprintf (stderr, "error: invalid IPv4 format.\n");
return 1;
}
for (int i = 0; i < QUAD; i++) /* loop over each quad */
if (ip[i] < 0 || 255 < ip[i]) { /* validate 0-255 */
fprintf (stderr, "error: invalid quad '%d'.\n", ip[i]);
return 1;
}
if (nl != '\n') { /* validate following char is '\n' */
fprintf (stderr, "error: additional characters following IP.\n");
return 1;
}
printf ("valid IP: %s", buf); /* all tests passed - good address */
return 0;
}
So here
Code:
if (sscanf (buf, "%d.%d.%d.%d%c", /* parse with sscanf */
&ip[0], &ip[1], &ip[2], &ip[3], &nl) != 5){
fprintf (stderr, "error: invalid IPv4 format.\n");
return 1;
}
I have never used sscanf before btw.
So buf is where the program is reading from, then this here "%d.%d.%d.%d%c" now these dots there.
Does this mean, that I need to put these dots in stdin because sscanf just sees these 3 dots between numbers so they need to be in stdin as well.
And this %c, so this %c char is put into &nl, and later on in the code its said
Code:
if (nl != '\n') { /* validate following char is '\n' */
fprintf (stderr, "error: additional characters following IP.\n");
return 1;
, now does stdin actually save when I press enter as an \n character?
And also this !=5, now I understand the if(...) and what !=5 means.
(sscanf (buf, "%d.%d.%d.%d%c", &ip[0], &ip[1], &ip[2], &ip[3], &nl) != 5)
But what is it looking for here the !=5, what should be equal to 5.
Is the !=5 so that the 5 &, every single & gets a value?
When i write (a!=4) ik that if a is 4 the statement is false.