C++如何将 IP 地址转换为字节

C++ how to convert ip address to bytes?

本文关键字:转换 字节 地址 IP C++      更新时间:2023-10-16

如何在C++中将IP地址转换为字节?基本上如何解析 IP 地址?例如,如果我有一个等于 121.122.123.124 的字符串。我需要解析它,以便byte1 = 121byte2 = 122byte3 = 123byte4 = 124

使用 sscanf() 函数:

#include <cstdio>
char arr[] = "192.168.1.102"; 
unsigned short a, b, c, d;
sscanf(arr, "%hu.%hu.%hu.%hu", &a, &b, &c, &d);

使用 inet_aton .

#include <arpa/inet.h>
#include <string>
#include <iostream>
int
main(int argc, char *argv[])
{
  std::string s;
  in_addr addr;
  while(std::cin >> s && inet_aton(s.c_str(), &addr)) {
    std::cout << inet_ntoa(addr) << "n";
  }
}

如果模式是常数,数字点数字点等,则使用istringstream:

#include <sstream>
using namespace std;
int byte1, byte2, byte3, byte4;
char dot;
char *ipaddress = "121.122.123.124";
istringstream s(ipaddress);  // input stream that now contains the ip address string
s >> byte1 >> dot >> byte2 >> dot >> byte3 >> dot >> byte4 >> dot;

试试这个:

char ipstr[] = "121.122.123.124";
char *marker, *ret;
unsigned char b1, b2, b3, b4;
ret = strtok_r(ipstr, ".", &marker);
b1 = (unsigned char)strtod(ret, NULL);
ret = strtok_r(NULL, ".", &marker);
b2 = (unsigned char)strtod(ret, NULL);
ret = strtok_r(NULL, ".", &marker);
b3 = (unsigned char)strtod(ret, NULL);
ret = strtok_r(NULL, ".", &marker);
b4 = (unsigned char)strtod(ret, NULL);