SHARE
TWEET

postgresql: calculates next subnet's address

alex0b Feb 4th, 2012 61 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #include "postgres.h"
  2. #include "fmgr.h"
  3. #include "catalog/pg_type.h"
  4. #include "utils/builtins.h"
  5. #include "utils/inet.h"
  6.  
  7. #ifdef PG_MODULE_MAGIC
  8. PG_MODULE_MAGIC;
  9. #endif
  10.  
  11. #define ip_bits(inetptr) \
  12.      (((inet_struct *) VARDATA_ANY(inetptr))->bits)
  13.  
  14. #define ip_addr(inetptr) \
  15.      (((inet_struct *) VARDATA_ANY(inetptr))->ipaddr)
  16.  
  17. Datum cidr_inc( PG_FUNCTION_ARGS);
  18. PG_FUNCTION_INFO_V1( cidr_inc );
  19. Datum
  20. cidr_inc( PG_FUNCTION_ARGS )
  21. {
  22.     inet *src = PG_GETARG_INET_P(0);
  23.     int bits = ip_bits(src); //netmask length
  24.    
  25.     inet *dst = (inet *) palloc(VARSIZE_ANY(src));
  26.     memcpy(dst, src, VARSIZE_ANY(src));
  27.    
  28.     int i = bits / 8;
  29.     ip_addr(dst)[i] += 1 << (8 - (bits % 8));
  30.     while(i > 0 && ip_addr(dst)[i--] == 0){
  31.         ++ip_addr(dst)[i];
  32.     }
  33.    
  34.     PG_RETURN_INET_P( dst );
  35. }
RAW Paste Data
Top