When sscanf is used to parse strings, it is easy to handle errors: sscanf returns the number of domains actually parsed and assigned values to determine if they are consistent with the expected values.
Today, we encountered a resolution address bug because the address book "127.0.0.1: 30000" was written as "127.0.0.1: 30000: 127.0.0.1: 30000". It was originally parsed using sscanf, if the result is equal to 5, it is considered correct, but no additional characters are determined.
Fixed:
Bool assign (const char * SRC)
{
Unsigned int B1, B2, B3, B4;
Char dummy; // catch extra Character
Int COUNT = sscanf (SRC, "% u. % u % C
", & B1, & B2, & B3, & B4, & dumm
Y );
If (COUNT = 4 & B1 <256 & b2 <256 & B3 <256 & B4 <256)
{
Assign (unsigned char) B1, (unsigned char) B2, (unsigned char) B3, (unsigned char) B4 );
Return true;
}
Return false;
}
Then read an extra character. If it matches, it is an error.
Another method is to use % N:
Bool assign (const char * SRC)
{
Unsigned int B1, B2, B3, B4;
Int bytes_parsed ;//
Int COUNT = sscanf (SRC, "% u. % u % N
", & B1, & B2, & B3, & B4 ,&
Bytes_parsed
);
If (COUNT = 4 & bytes_parsed =
Strlen (SRC)
& B1 <256 & b2 <256 & B3 <256 & B4 <256)
{
Assign (unsigned char) B1, (unsigned char) B2, (unsigned char) B3, (unsigned char) B4 );
Return true;
}
Return false;
}
% N puts the number of bytes read into the int type result.