#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);
}
I2luY2x1ZGUgPGNzdHJpbmc+CiNpbmNsdWRlIDxpb3N0cmVhbT4KI2luY2x1ZGUgPGNzdGRsaWI+CnVzaW5nIHN0ZDo6c3RyaW5nOwp1c2luZyBzdGQ6OmNvdXQ7CnVzaW5nIHN0ZDo6bWVtY3B5OwoKbmFtZXNwYWNlIHB0dF9kZW1vIHsKCnVuaW9uIElQdjQgewogICAgaW50IF9pOwogICAgc3RydWN0IHsKICAgICAgICB1bnNpZ25lZCBjaGFyIGIxLCBiMiwgYjMsIGI0OwogICAgfSBfZDsKfTsKCmludCBpbmV0X3B0b240IChjaGFyIGNvbnN0ICpz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yk7CgogICAgICAgICAgICBpZiAoc2F3X2RpZ2l0ICYmICp0cCA9PSAwKQogICAgICAgICAgICAgICAgcmV0dXJuICgwKTsKICAgICAgICAgICAgaWYgKG5ld3YgPiAyNTUpCiAgICAgICAgICAgICAgICByZXR1cm4gKDApOwoKICAgICAgICAgICAgKnRwID0gbmV3djsKCiAgICAgICAgICAgIGlmICghc2F3X2RpZ2l0KSB7CiAgICAgICAgICAgICAgICBpZiAoKytvY3RldHMgPiA0KQogICAgICAgICAgICAgICAgICAgIHJldHVybiAoMCk7CiAgICAgICAgICAgICAgICBzYXdfZGlnaXQgPSAxOwogICAgICAgICAgICB9CiAgICAgICAgfQogICAgICAgIGVsc2UgaWYgKGNoID09ICcuJyAmJiBzYXdfZGlnaXQpIHsKICAgICAgICAgICAgaWYgKG9jdGV0cyA9PSA0KQogICAgICAgICAgICAgICAgcmV0dXJuICgwKTsKICAgICAgICAgICAgKisrdHAgPSAwOwogICAgICAgICAgICBzYXdfZGlnaXQgPSAwOwogICAgICAgIH0KICAgICAgICBlbHNlCiAgICAgICAgICAgIHJldHVybiAoMCk7CiAgICB9CiAgICBpZiAob2N0ZXRzIDwgNCkKICAgICAgICByZXR1cm4gKDApOwogICAgbWVtY3B5IChkc3QsIHRtcCwgTlNfSU5BRERSU1opOwogICAgcmV0dXJuICgxKTsKfQo=