如何在C ++中将ip地址转换为字节?基本上我该如何解析IP地址?例如,如果我有一个等于121.122.123.124
的字符串。
我需要解析这个byte1 = 121
,byte2 = 122
,byte3 = 123
,byte4 = 124
。
答案 0 :(得分:3)
使用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);
答案 1 :(得分:3)
使用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";
}
}
答案 2 :(得分:1)
如果模式是常量,数字点数点等,则使用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;
答案 3 :(得分:0)
试试这个:
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);