Tuesday, September 20, 2011

creating sockets in c

Creating Sockets

In this post, you see that creating sockets can be almost as easy as creating a pipe. There are a few more function arguments however, which you will learn about. These arguments must be supplied with suitable values to be successful. The function socketpair(2) synopsis is as follows:

#include <sys/types.h>
#include <sys/socket.h>
int socketpair(int domain, int type, int protocol, int sv[2]);

The include file sys/types.h is required to define some C macro constants. The include file sys/socket.h is necessary to define the socketpair(2) function prototype. The socketpair(2) function takes four arguments. They are
  • The domain of the socket. 
  • The type of the socket. 
  • The protocol to be used. 
  • The pointer to the array that will receive file descriptors that reference the created sockets.
The domain argument's explanation will be deferred until my next post "Domain and Address Family". For the purpose of the socketpair(2) function, however, always supply the C macro value AF_LOCAL. The type argument declares what type of socket you want to create. The choices for the socketpair(2) function are
The implication of the socket choice will be explored "Socket Types andProtocols" For this chapter, we'll simply use SOCK_STREAM for the type of the socket. For the socketpair(2) function, the protocol argument must be supplied as zero.

The argument sv[2] is a receiving array of two integer values that represent two sockets. Each file descriptor represents one socket (endpoint) and is otherwise indistinguishable from the other. If the function is successful, the value zero is returned. Otherwise, a return value of -1 indicates that a failure has occurred, and that errno should be consulted for the specific reason.

Always test the function return value for success or failure. The value errno should only be consulted when it has been determined that the function call has indicated that it failed. Only errors are posted to errno; it is never cleared to zero upon success.


No comments:

Post a Comment