1

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

4

4 回答 4

4

使用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);
于 2012-04-28T19:21:24.547 回答
4

使用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";
  }
}
于 2012-04-28T21:01:17.003 回答
2

如果模式是恒定的,数字点数字点等,则使用 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;
于 2012-04-28T19:15:59.350 回答
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);
于 2012-04-28T19:09:53.637 回答