3

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.

Anurag
  • 143
  • 1
  • 9
  • Use the `inet_addr()` function to parse a dotted quad. – Barmar Oct 24 '13 at 05:57
  • OT: The format specifier for `unsigned short int` should be `%hu`. `%d` expects a `signed int`. – alk Oct 24 '13 at 06:04
  • would hex format be good for you ("%x"), forcing the user to convert his ip address to ea070701 for example (234.7.7.1)? – NiRR Oct 24 '13 at 06:04

2 Answers2

3
#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).

damienfrancois
  • 52,978
  • 9
  • 96
  • 110
  • You should also use `%hhu` for printing. – 0xF1 Oct 24 '13 at 06:40
  • I'm getting different output `C:\Codes>ip_address_test.exe 8.8.8.8 0 0 0 8 C:\Codes>` And this error when compiling it `unknown conversion type character 'h' in format` Full codes and error here ... https://pastebin.com/0qqwY7uR –  Mar 11 '18 at 01:40
0

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.

armitus
  • 712
  • 5
  • 20
  • 1
    Thank you for contributing an answer on SO! Please insert your code as text, and not as picture. See https://meta.stackoverflow.com/questions/285551/why-not-upload-images-of-code-on-so-when-asking-a-question for more information. – armitus Apr 17 '19 at 20:34