Add Book to My BookshelfPurchase This Book Online

Chapter 14 - Networking with Sockets

UNIX Systems Programming for SVR4
David A. Curry
 Copyright © 1996 O'Reilly & Associates, Inc.

Creating a Socket
The basic unit of communication in the Berkeley networking paradigm is the socket, created with the socket function:
    #include <sys/types.h>
    #include <sys/socket.h>
    int socket(int domain, int type, int protocol);
The domain argument specifies the domain, or address family, in which addresses should be interpreted; it imposes certain restrictions on the length of addresses, and what they mean. In the last chapter, we used the AF_UNIX domain, in which addresses are ordinary UNIX pathnames. In this chapter, we will look at the AF_INET domain, which is used for Internet addresses.
There are two types of communications channels supported by sockets, selected with the type argument:
SOCK_STREAM
This type of connection is usually called a virtual circuit. It is a bidirectional continuous byte stream that guarantees the reliable delivery of data in the order in which it was sent. No data can be sent until the circuit is established; the circuit then remains intact until the conversation is complete. A telephone call is a real-world example of a virtual circuit; a FIFO is another example. Virtual circuits are implemented in the Internet domain using the Internet-standard Transmission Control Protocol (TCP).
SOCK_DGRAM
This type of connection is used to send discrete packets of information called datagrams. Datagrams are not guaranteed to be delivered to the remote side of the communications channel in the same order they were sent. In fact, they are not guaranteed to be delivered at all. (This is not as undesirable as it may sound; there are many applications for which it is perfectly suited.) The U.S. mail system is a real-world example of datagrams: each letter is an individual message, letters may arrive in a different order than they were sent, and some may even get lost. Datagrams are implemented in the Internet domain using the Internet-standard User Datagram Protocol (UDP).
The protocol parameter specifies the protocol number that should be used on the socket; it is usually the same as the address family. In the last chapter we used the PF_UNIX protocol family; in this chapter we will use the PF_INET family. The protocol parameter can usually be specified as 0, and the system will figure it out.
When a socket is successfully created, a socket descriptor is returned. This is a small non-negative integer, similar to a file descriptor (but with slightly different semantics). If the socket cannot be created, -1 is returned and the error information is stored in errno.

Previous SectionNext Section
Books24x7.com, Inc © 2000 –  Feedback