#include <cstring>
#include <iostream>
#include <cstdlib>
using std::string;
using std::cout;
using std::memcpy;

namespace ptt_demo {

union IPv4 {
    int _i;
    struct {
        unsigned char b1, b2, b3, b4;
    } _d;
};

int inet_pton4 (char const *src, unsigned char *dst);

}

int main() {
    std::string str_ip("140.127.34.222");
    ptt_demo::IPv4 ip;

    ptt_demo::inet_pton4(str_ip.c_str(), (unsigned char*)&(ip._i));

    std::cout << str_ip << " in integer form is: " << ip._i
              << "...(why would you want to see the value?)\n"

              << "It also equals to "
              << (int)ip._d.b1 << '.'
              << (int)ip._d.b2 << '.'
              << (int)ip._d.b3 << '.'
              << (int)ip._d.b4 << '\n';

}

#define NS_INADDRSZ 4
int ptt_demo::inet_pton4 (char const *src, unsigned char *dst) {
    int saw_digit, octets, ch;
    unsigned char tmp[NS_INADDRSZ], *tp;

    saw_digit = 0;
    octets = 0;
    *(tp = tmp) = 0;
    while ((ch = *src++) != '\0') {
        if (ch >= '0' && ch <= '9') {
            unsigned newv = *tp * 10 + (ch - '0');

            if (saw_digit && *tp == 0)
                return (0);
            if (newv > 255)
                return (0);

            *tp = newv;

            if (!saw_digit) {
                if (++octets > 4)
                    return (0);
                saw_digit = 1;
            }
        }
        else if (ch == '.' && saw_digit) {
            if (octets == 4)
                return (0);
            *++tp = 0;
            saw_digit = 0;
        }
        else
            return (0);
    }
    if (octets < 4)
        return (0);
    memcpy (dst, tmp, NS_INADDRSZ);
    return (1);
}
