You could use format specifier %hhu.%hhu.%hhu.%hhu
, which reads in unsigned 8 bit values, and you could directly read into the 4 bytes of your int-representation of an ip-address, respectively:
int main () {
const char* testLine = "aName 192.168.112.54 100";
char name[100];
int speed;
volatile uint32_t ipAddress=0;
unsigned char* ipAddressBytes = (unsigned char*)&ipAddress;
if (sscanf(testLine, "%s %hhu.%hhu.%hhu.%hhu %d", name, ipAddressBytes+3, ipAddressBytes+2,ipAddressBytes+1,ipAddressBytes+0, &speed) == 6) {
printf("%s %08X %d\n",name, ipAddress, speed);
}
return 0;
}
Output:
aName C0A87036 100
Format %hhu
reads in an integral value and maps it to 8 bits; hence, it does not check if the input concerning the IP-address is valid in the sense that 1025.168.112.54
would not be valid. However, it avoids technical overflows in that any part exceeding 8 bits is simply ignored. So before mentioned input would yield 01A87036
.
Note the volatile
-specifier, which tells the compiler that it shall not optimize access to this variable; otherwise, the compiler might assume that - since the value is not obviously changed - the variable is unchanged / not initialized.
Note further that you have to take care whether your environment is of big endian or little endian architecture.
Hope it helps.