在C中输入IP地址 [英] IP address input in C

查看:223
本文介绍了在C中输入IP地址的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在C中编写一个程序,它从用户那里获取输入IP地址,然后我想对它进行一些位操作。我怎么能用C中的位输入。我尝试了下面的代码,但整数大小为2字节,这使得这里的完整地址为8字节(64位)。使用char扫描输入时,会丢失输入的值。有没有办法以位为单位输入(我想要32位仅32位IPv4地址和128位仅128位V6)。

  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);

提前致谢。

解决方案

  #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);
返回0;
}

给出

  $ gcc tc&& ./a.out<<< 12.12.12.12 
12 12 12 12

例如参见此参考,根据目标变量的类型(文档中的第3个表)查找要使用的说明符。 / p>

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.

解决方案

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

这篇关于在C中输入IP地址的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆