C++ 中将 IP 地址转换为十六进制的程序


输入 IP 地址值,任务是将给定的 IP 地址表示为其十六进制等效值。

什么是 IP 地址

IP 地址或 Internet 协议是一个唯一编号,可唯一描述连接到网络的硬件。Internet 意味着在网络上,且协议定义了连接时必须遵循的一组规则和规定。由于 IP 地址,系统才可能通过网络与另一个系统通信。IP 有两个版本,即 −

  • IPv4(Internet 协议版本 4)
  • IPv6(Internet 协议版本 6)

IP 地址表示为数字序列,形式为 −

151.101.65.121

对于此转换,以下程序使用了为 Internet 操作创建的头文件“arpa/inet.h”

示例

Input-: 127.0.0.1
Ouput-: 0x7f000001
Input-: 172.31.0.2
Output-: 0xac1f0002

算法

Start
Step1-> Declare function to reverse
   void reverse(char* str)
      set int len = 2
      set int r = strlen(str) – 2
      Loop While (len < r)
         call swap(str[len++], str[r++])
         Call swap(str[len++], str[r])
         Set r = r – 3
      End
   End
Step 2-> Declare function to convert IP address to hexadecimal
   void convert(int ip_add)
      declare char str[15]
      call sprintf(str, "0x%08x", ip_add)
      call reverse(str)
      print str
step 3-> In main()
   declare int ip_add = inet_addr("127.0.0.1")
   call convert(ip_add)
Stop

示例

 动态演示

#include <arpa/inet.h>
#include <iostream>
#include <string.h>
using namespace std;
//reverse hexadecimal number
void reverse(char* str) {
   int len = 2;
   int r = strlen(str) - 2;
   while (len < r) {
      swap(str[len++], str[r++]);
      swap(str[len++], str[r]);
      r = r - 3;
   }
}
//Convert IP address to heaxdecimal
void convert(int ip_add) {
   char str[15];
   sprintf(str, "0x%08x", ip_add);
   reverse(str);
   cout << str << "\n";
}
int main() {
   int ip_add = inet_addr("127.0.0.1");
   convert(ip_add);
   return 0;
}

输出

如果我们运行以上代码,它将生成以下输出

0x7f000001

更新于:18-Oct-2019

647 次浏览

开启您的职业生涯

通过完成课程获得认证

开始
广告
© . All rights reserved.