Question

I want to write a program in C which is taking input IP Address from user and then i want to do some bit operations on it. How can i take input in bits in C. I tried the below code but integer is of size 2 bytes, which makes the complete address here of 8 bytes(64 bits). When using char to scan input, its losing the value entered. Is there any way to take input in bits( i want 32 bits IPv4 address in 32 bits only and 128bit V6 in 128 bits only).

    unsigned short int a,b,c,d;
scanf("%d.%d.%d.%d", &a,&b,&c,&d);
printf("%d\t%d\t%d\t%d\t", a, b, c, d);

Thanks in advance.

Was it helpful?

Solution

#include <stdio.h>

int main(void)
{
      unsigned char a,b,c,d;
      scanf("%hhu.%hhu.%hhu.%hhu", &a,&b,&c,&d);
      printf("%hhu\t%hhu\t%hhu\t%hhu\t", a, b, c, d);
      return 0;
}

gives

$ gcc t.c && ./a.out <<< 12.12.12.12
12  12  12  12

See for instance this reference to find which specifier to use depending on the type of the target variables (3rd table in the document).

OTHER TIPS

Use %*c along with %d for ignoring the dot in between the numbers.

Try the code here ;

IP address program

this will give out the ouput as ;

enter the ip address : 23.145.189.214
the entered ip address is 23.145.189.214

make sure to use "." when displaying the address in printf function. The dot operator does not work when taking input as you have shown is due to the fact the compiler doesn't know what to do with it. It appears as an unidentified character and execution stops.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top