Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is in_addr?

Tags:

php

When looking at the return value of inet_pton and the parameter of inet_ntop in the PHP manual, it refers to in_addr in both cases.

A quick search leads me to the MSDN Dev Center with this answer:

The in_addr structure represents an IPv4 Internet address.

But this still doesn't explain what the "structure" actually is. When testing return values with inet_pton (using a random IP like 219.225.174.153) I get strange chars returned such as €·Æô.

So what exactly is the "structure" of in_addr that PHP and MSDN is referring to?

like image 694
doitlikejustin Avatar asked Oct 07 '13 19:10

doitlikejustin


1 Answers

inet_pton() turns a human-readable IP address into a 4-byte binary string used for network operations, usually involving raw sockets. Those "strange characters" are the ASCII character representations of the numbers 219, 225, 174, and 153 and may or may not have their byte order reversed to reflect the 'endian-ness' of your system.

Every IPv4 address is essentially a 32-bit unsigned integer, and we create an easy-to understand representation of this number by splitting it into 4 separate 8-bit numbers [0 to 255] for what is called "dotted quad" notation.

dotted quad example

I would suggest looking at and/or using ip2long() and long2ip() if you're simply looking for a more efficient storage of IP address data, and not raw network programming.

like image 54
Sammitch Avatar answered Sep 26 '22 16:09

Sammitch