fork(1) download
  1. #include <cstring>
  2. #include <iostream>
  3. #include <cstdlib>
  4. using std::string;
  5. using std::cout;
  6. using std::memcpy;
  7.  
  8. namespace ptt_demo {
  9.  
  10. union IPv4 {
  11. int _i;
  12. struct {
  13. unsigned char b1, b2, b3, b4;
  14. } _d;
  15. };
  16.  
  17. int inet_pton4 (char const *src, unsigned char *dst);
  18.  
  19. }
  20.  
  21. int main() {
  22. std::string str_ip("140.127.34.222");
  23. ptt_demo::IPv4 ip;
  24.  
  25. ptt_demo::inet_pton4(str_ip.c_str(), (unsigned char*)&(ip._i));
  26.  
  27. std::cout << str_ip << " in integer form is: " << ip._i
  28. << "...(why would you want to see the value?)\n"
  29.  
  30. << "It also equals to "
  31. << (int)ip._d.b1 << '.'
  32. << (int)ip._d.b2 << '.'
  33. << (int)ip._d.b3 << '.'
  34. << (int)ip._d.b4 << '\n';
  35.  
  36. }
  37.  
  38. #define NS_INADDRSZ 4
  39. int ptt_demo::inet_pton4 (char const *src, unsigned char *dst) {
  40. int saw_digit, octets, ch;
  41. unsigned char tmp[NS_INADDRSZ], *tp;
  42.  
  43. saw_digit = 0;
  44. octets = 0;
  45. *(tp = tmp) = 0;
  46. while ((ch = *src++) != '\0') {
  47. if (ch >= '0' && ch <= '9') {
  48. unsigned newv = *tp * 10 + (ch - '0');
  49.  
  50. if (saw_digit && *tp == 0)
  51. return (0);
  52. if (newv > 255)
  53. return (0);
  54.  
  55. *tp = newv;
  56.  
  57. if (!saw_digit) {
  58. if (++octets > 4)
  59. return (0);
  60. saw_digit = 1;
  61. }
  62. }
  63. else if (ch == '.' && saw_digit) {
  64. if (octets == 4)
  65. return (0);
  66. *++tp = 0;
  67. saw_digit = 0;
  68. }
  69. else
  70. return (0);
  71. }
  72. if (octets < 4)
  73. return (0);
  74. memcpy (dst, tmp, NS_INADDRSZ);
  75. return (1);
  76. }
  77.  
Success #stdin #stdout 0.02s 2856KB
stdin
Standard input is empty
stdout
140.127.34.222 in integer form is: -568164468...(why would you want to see the value?)
It also equals to 140.127.34.222