Hello,

I have a feature request: How about adding a built-in function to convert
IP addresses from strings to "INT UNSIGNED", and another function to
convert vice versa.

This makes it easier for e.g. people whose web applications log IP
addresses in MySQL; it is more efficient to store IP addresses as INT
UNSIGNED than VARCHAR(10). Also, mask operations (e.g. '&' and '|') can be
performed on INT UNSIGNED.

I have attached two C functions (ip2num to convert from string to unsigned
long, and num2ip to convert from unsigned long to string) that could be
used as code if someone decides to make a built-in function for this.

-Philip Mak ([EMAIL PROTECTED])
/* ip.c
 *
 * Functions for converting IP addresses between strings and
 * unsigned long int.
 */

unsigned long ip2num(char *char_ip) {
  char num_ip[5];
  unsigned long *long_ip;

  num_ip[4] = 0;
  sscanf(char_ip, "%d.%d.%d.%d", num_ip, num_ip+1, num_ip+2, num_ip+3);
  long_ip = (unsigned long *) num_ip;
  return *long_ip;
}

char *num2ip(unsigned long num_ip) {
  static char char_ip[10];
  char *ips;

  ips = (char *) &num_ip;
  sprintf(char_ip, "%d.%d.%d.%d",
          (unsigned char) *ips, (unsigned char) *(ips+1),
          (unsigned char) *(ips+2), (unsigned char) *(ips+3));
  return char_ip;
}

main() {
  unsigned long ip;

  ip = ip2num("64.29.16.235");
  printf("64.29.16.235 = %lu\n", ip);
  printf("%lu = %s\n", ip, num2ip(ip));
}
---------------------------------------------------------------------
Before posting, please check:
   http://www.mysql.com/manual.php   (the manual)
   http://lists.mysql.com/           (the list archive)

To request this thread, e-mail <[EMAIL PROTECTED]>
To unsubscribe, e-mail <[EMAIL PROTECTED]>
Trouble unsubscribing? Try: http://lists.mysql.com/php/unsubscribe.php

Reply via email to