Hacking - The Art of Exploitation, 2nd Edition

(Romina) #1
Networking 199

Datagram sockets and UDP are commonly used in networked games and


streaming media, since developers can tailor their communications exactly


as needed without the built-in overhead of TCP.


0x421 Socket Functions..........................................................................


In C, sockets behave a lot like files since they use file descriptors to identify


themselves. Sockets behave so much like files that you can actually use the


read() and write() functions to receive and send data using socket file descrip-


tors. However, there are several functions specifically designed for dealing


with sockets. These functions have their prototypes defined in /usr/include/


sys/sockets.h.


socket(int domain, int type, int protocol)


Used to create a new socket, returns a file descriptor for the socket or
-1on error.

connect(int fd, struct sockaddr *remote_host, socklen_t addr_length)


Connects a socket (described by file descriptor fd) to a remote host.
Returns 0 on success and -1 on error.

bind(int fd, struct sockaddr *local_addr, socklen_t addr_length)


Binds a socket to a local address so it can listen for incoming connections.
Returns 0 on success and -1 on error.

listen(int fd, int backlog_queue_size)


Listens for incoming connections and queues connection requests up to
backlog_queue_size. Returns 0 on success and -1 on error.

accept(int fd, sockaddr remote_host, socklen_t addr_length)


Accepts an incoming connection on a bound socket. The address infor-
mation from the remote host is written into the remote_host structure and
the actual size of the address structure is written into *addr_length. This
function returns a new socket file descriptor to identify the connected
socket or -1 on error.

send(int fd, void *buffer, size_t n, int flags)


Sends n bytes from *buffer to socket fd; returns the number of bytes sent
or -1 on error.

recv(int fd, void *buffer, size_t n, int flags)


Receives n bytes from socket fd into *buffer; returns the number of bytes
received or -1 on error.

When a socket is created with the socket() function, the domain, type,


and protocol of the socket must be specified. The domain refers to the pro-


tocol family of the socket. A socket can be used to communicate using a


variety of protocols, from the standard Internet protocol used when you


browse the Web to amateur radio protocols such as AX.25 (when you are


being a gigantic nerd). These protocol families are defined in bits/socket.h,


which is automatically included from sys/socket.h.

Free download pdf