C++ how to convert ip address to bytes?

后端 未结 4 1718
借酒劲吻你
借酒劲吻你 2021-01-07 08:54

How would I convert an ip address into bytes in C++? Basically how do I parse the IP address? For example, if I have a string equal to 121.122.123.124. I need

相关标签:
4条回答
  • 2021-01-07 09:38

    Try this:

    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);
    
    0 讨论(0)
  • 2021-01-07 09:43

    If the pattern is constant, number dot number dot etc, then use 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;
    
    0 讨论(0)
  • 2021-01-07 09:51

    Using sscanf() function:

    #include <cstdio>
    
    char arr[] = "192.168.1.102"; 
    unsigned short a, b, c, d;
    sscanf(arr, "%hu.%hu.%hu.%hu", &a, &b, &c, &d);
    
    0 讨论(0)
  • 2021-01-07 09:52

    Use 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";
      }
    }
    
    0 讨论(0)
提交回复
热议问题