IP address input in C

时光怂恿深爱的人放手 提交于 2019-12-22 18:28:48

问题


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.


回答1:


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




回答2:


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.



来源:https://stackoverflow.com/questions/19558013/ip-address-input-in-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!