C++如何将 IP 地址转换为字节
C++ how to convert ip address to bytes?
如何在C++中将IP地址转换为字节?基本上如何解析 IP 地址?例如,如果我有一个等于 121.122.123.124
的字符串。我需要解析它,以便byte1 = 121
、byte2 = 122
、byte3 = 123
、byte4 = 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);
相关文章:
- 将Integer转换为4字节的unsined字符矢量(按大端字节顺序)
- 将字节数组转换为带有字节序问题的指针
- 使用 stbi_write_png,如何将 0 和 1 的矩形字节数组转换为单色 png 文件?
- 如何在连接器 C++ 中将原始字节转换为字符串
- 如何在C++(Arduino)中将浮点数组转换为字节数组
- 将字节数组转换为多维数组
- C++如何将字符数组转换为字节向量(向量<byte>)
- 如何在C++中将字节向量(std::vector<uint8_t>)转换为不同的uint32_t,uint16_t和uint8_t变量
- 将字符串转换为无符号字符数组/字节数组
- 将(N 个字节)无符号字符指针转换为浮点数和双 C++
- 将以 null 结尾的字节字符串转换为原始字符串文本
- 正在转换结构数据的字节序
- 如何将 CString 转换为字节 [] 数组?
- 一种将 Dart 中的字节数据转换为 C++ 中的无符号字符*的有效方法?
- 使用 ESP8266/8285 将字符串从 Web 服务器转换为字节数组
- 编译时将字符*转换为字节
- 将字节数组转换为对象C++ |C++中的 C# 位转换器
- C++转换字节
- 将整型转换字节中的字节更改为整数
- c++从字符串化字节转换字节数组