【问题标题】:IP address input in CC中输入的IP地址
【发布时间】:2013-11-02 16:37:54
【问题描述】:

我想用 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);

提前致谢。

【问题讨论】:

  • 使用inet_addr() 函数解析一个虚线四边形。
  • OT:unsigned short int 的格式说明符应为 %hu%d 需要 signed int
  • 十六进制格式对你有好处吗(“%x”),强制用户将他的IP地址转换为ea070701,例如(234.7.7.1)?

标签: c ip bits


【解决方案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;
}

给予

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

请参阅 this reference 以根据目标变量的类型(文档中的第 3 个表)查找要使用的说明符。

【讨论】:

  • 您还应该使用%hhu 进行打印。
  • 我得到不同的输出C:\Codes&gt;ip_address_test.exe 8.8.8.8 0 0 0 8 C:\Codes&gt; 编译时出现此错误unknown conversion type character 'h' in format 此处为完整代码和错误... pastebin.com/0qqwY7uR
【解决方案2】:

使用%*c%d 来忽略数字之间的点。

试试这里的代码;

IP address program

这将输出为 ;

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

确保在 printf 函数中显示地址时使用"."。如您所见,点运算符在输入时不起作用,这是因为编译器不知道如何处理它。它显示为身份不明的角色,执行停止。

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2020-05-19
  • 1970-01-01
  • 2012-06-23
  • 2013-01-23
  • 2022-11-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多