PrzMas

ip2long, long2ip

Apr 29th, 2016
98
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Pawn 1.45 KB | None | 0 0
  1. #define IP_MAXLEN 15
  2.  
  3. stock ipcmp(ip1, ip2, mask= 0xffffffff) return ip1&mask == ip2&mask;
  4.  
  5. stock ip2long(ip[])
  6. {
  7.   new res= 0x00000000, oct= 0;
  8.   for(new idx= 0, val= 0, len= strlen(ip); oct < 4 && idx < len; oct++, idx++, val= 0)
  9.   {
  10.     for(new i= idx, j= 2; i < len-1; i++)
  11.     {
  12.       if (i-idx >= j) return 0x00000000;
  13.       else if ('0' <= ip[i] <= '9') idx++;
  14.       else if (ip[i] == '*') { j= 1; val= 255; break; }
  15.       else if (ip[i] == '.') { idx= i; break; }
  16.       else return 0x00000000;
  17.     }
  18.     if (ip[idx] == '.' && (idx == 0 || ip[--idx] == '.')) return 0x00000000;
  19.     if (ip[idx] != '*') for(new i= idx, exp= 1; i >= 0 && ip[i] != '.'; i--)
  20.     {
  21.       if (!('0' <= ip[i] <= '9') || idx-i > 2) return 0x00000000;
  22.       val += (ip[i]-'0')*exp; exp *= 10;
  23.       if (val > 255) return 0x00000000;
  24.     }
  25.     res <<= 8; res += val; idx++;
  26.   }
  27.  
  28.   if (oct < 4) return 0x00000000
  29.   else return res << ((4-oct)*8);
  30. }
  31.  
  32. stock long2ip(ip, mask= 0xffffffff, bool: wildcards= false)
  33. {
  34.   new res[IP_MAXLEN+1];
  35.   for(new ip2= ip&mask, idx= 0, i= 0, oct= 1; oct <= 4; ip2 <<= 8, idx++, i= 0, oct++)
  36.   {
  37.     new str[3+1];
  38.     for(new val= ip2 >>> 24; val > 0 || i == 0; i++)
  39.     {
  40.       if (wildcards && val == 0x00) { str[i++]= '*'; break; }
  41.       else { str[i]= (val%10)+'0'; val /= 10; }
  42.     }
  43.     for(--i; i >= 0 && idx < IP_MAXLEN; i--) res[idx++]= str[i];
  44.     if (oct < 4 && idx < IP_MAXLEN) res[idx]= '.';
  45.   }
  46.  
  47.   return res;
  48. }
Advertisement
Add Comment
Please, Sign In to add comment