Jump to content

The best way to store an IP address in the database?

- - - - -

  • Please log in to reply
3 replies to this topic

#1
Fighter

Fighter

    Newbie

  • Members
  • PipPip
  • 28 posts
After writing a few good applications that require storing the IP in the database, I had always wondered what is the norm for this thing, what I had been doing (and had seen) is creating a 15 max length varchar column and storing it in human readable format.

Do you think there is a more efficient way or built in function for MySQL? What would be the disadvantages/advantages of using them?

#2
Alexander

Alexander

    It's Science!

  • Moderators
  • 4,124 posts
  • Location:Vancouver, Eh! Cleverness: 200
They are actually very similar to timestamps, in fact they are just four bytes separated by dots, four bytes can perfectly fit in to an integer (opposed to 15 bytes of charactes)

MySQL borrows the rfc defined functions for INET (ipv4) from C, and can be used as follows:

mysql> SELECT INET_ATON('11.22.33.44');
+--------------------------+
| INET_ATON('11.22.33.44') |
+--------------------------+
|                185999660 |
+--------------------------+
1 row in set (0.00 sec)

mysql> SELECT INET_NTOA(185999660);
+----------------------+
| INET_NTOA(185999660) |
+----------------------+
| 11.22.33.44          |
+----------------------+
1 row in set (0.00 sec)

I am not sure if there are any major disadvantages, you can always convert them on the fly back to quad dotted form.
Be sure to read the updated FAQ! || Health is achieved through the same 10,000 steps.
If a suggested code/method fails, informing us is less important than telling us why or what errors occurred.

#3
Fighter

Fighter

    Newbie

  • Members
  • PipPip
  • 28 posts
You made my hour of planning worth it, I was wondering, are there any functions that are equivalent in PHP to do all this? I suppose there will be something down the road that will require me to work in-script.

#4
Alexander

Alexander

    It's Science!

  • Moderators
  • 4,124 posts
  • Location:Vancouver, Eh! Cleverness: 200
ip2long and long2ip if I recall, the only odd thing is that PHP cannot represent unsigned integers, they will store as them but if you were to display you'd need to use printf("%u"..)
Be sure to read the updated FAQ! || Health is achieved through the same 10,000 steps.
If a suggested code/method fails, informing us is less important than telling us why or what errors occurred.




1 user(s) are reading this topic

0 members, 1 guests, 0 anonymous users