Hacking - The Art of Exploitation, 2nd Edition

(Romina) #1
Networking 203

htons(short value) Host-to-Network Short


Converts a 16-bit integer from the host’s byte order to network byte order


ntohl(long value) Network-to-Host Long


Converts a 32-bit integer from network byte order to the host’s byte order


ntohs(long value) Network-to-Host Short


Converts a 16-bit integer from network byte order to the host’s byte order


For compatibility with all architectures, these conversion functions should


still be used even if the host is using a processor with big-endian byte ordering.


0x424 Internet Address Conversion


When you see 12.110.110.204, you probably recognize this as an Internet


address (IP version 4). This familiar dotted-number notation is a common


way to specify Internet addresses, and there are functions to convert this


notation to and from a 32-bit integer in network byte order. These functions


are defined in the arpa/inet.h include file, and the two most useful con-


version functions are:


inet_aton(char ascii_addr, struct in_addr network_addr)


ASCII to Network


This function converts an ASCII string containing an IP address in dotted-
number format into an in_addr structure, which, as you remember, only
contains a 32-bit integer representing the IP address in network byte
order.

inet_ntoa(struct in_addr *network_addr)


Network to ASCII


This function converts the other way. It is passed a pointer to an in_addr
structure containing an IP address, and the function returns a character
pointer to an ASCII string containing the IP address in dotted-number
format. This string is held in a statically allocated memory buffer in the
function, so it can be accessed until the next call to inet_ntoa(), when the
string will be overwritten.

0x425 A Simple Server Example


The best way to show how these functions are used is by example. The following


server code listens for TCP connections on port 7890. When a client connects,


it sends the message Hello, world! and then receives data until the connection


is closed. This is done using socket functions and structures from the include


files mentioned earlier, so these files are included at the beginning of the


program. A useful memory dump function has been added to hacking.h,


which is shown on the following page.

Free download pdf