中文网站
  Advanced Search
Read the latest Blogs from IT professionals in the field. Read and write community created documents. Need IT help? Ask our staff. Connect with your peers. Check our Tech Shop for posters, books and software tools. Home

11.1.3.3 Address format conversions

When working with IPv4 and IPv6 addresses, one often needs to convert their human-readable textual
representation into a binary numeric form and vice versa. The following two functions serve this
purpose:

The inet_pton function converts the textual representation into binary and inet_ntop the other way around. The binary form always uses the Network Byte Order.

The af argument specifies the address family (AF_INET or AF_INET6) and through the src and dst arguments the functions are given two pointers – src points to the buffer with the input value and dst to the buffer where the result is to be stored. Finally, the size argument of inet_ntop gives the size of the buffer allocated for the result. This buffer should be long enough to store a textual representation of any IPv4 or IPv6 address (depending on the chosen address family).

Function inet_pton returns 1 if the conversion was successful, 0 if the input value is considered wrong and -1 in the case of an unknown address family. In contrast, inet_ntop signals a failure by returning the NULL pointer, whereas if the conversion succeeds, the dst pointer is passed as the function return value, too.