I am trying to use to turn an IP address into a numerical string for mysql storage using the inet_pton() in the PHP code, yet this function either returns nothing or this: '�?i' NOTE: The IP address is a standard IPv4 (and not my localhost)
My code is: echo inet_pton($_SERVER['REMOTE_ADDR']);
The output of inet_pton()
is a binary string - nothing printable in most of the cases. You can try this with
echo inet_pton("65.66.67.68");
EDIT after feedback from @YWSW the question is, how to split the IP address in the string "173.63.155.19" in the 4 bytes 173, 63, 155 and 119
This could be achieved by
$ip_bytes=inet_pton($ip_string);
$ip_byte0=ord($ip_bytes[0]);
$ip_byte1=ord($ip_bytes[1]);
$ip_byte2=ord($ip_bytes[2]);
$ip_byte3=ord($ip_bytes[3]);
$ip_byte[0..3] are the 4 bytes you need.
Please understand, that I do NOT endorse storing an IP address in the DB as 4 ints!
Your code:
echo inet_pton($_SERVER['REMOTE_ADDR']);
Is converting a readeable IP from a normal string to a binary string (that my include NULL chars and other strange values, and therefore unreadeable). To represent your binary ip value back into a readeable string, use bin2hex(). Which will convert binary values into readeable hex strings:
echo bin2hex(inet_pton($_SERVER['REMOTE_ADDR']));
It doesn't quite end there: next matter is to consider which format you want to display it: IPv6 usually displays each binary byte as hex and has ':' every fourth hex, whereas IPv4 usually displays each binary byte as numerical values (not hex!) and has a '.' after each byte-to-number representation.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With