Chapter Contents

Previous

Next
socket

socket



Creates a Socket

Portability: UNIX compatible


SYNOPSIS
DESCRIPTION
RETURN VALUE
PORTABILITY
EXAMPLE
RELATED FUNCTIONS


SYNOPSIS

#include <sys/types.h>
#include <sys/socket.h>

int socket(int domain, int type, int protocol);


DESCRIPTION

socket creates an endpoint for communication and returns a descriptor, which is a small integer used to reference the socket.

domain
specifies the communications protocol family, using a symbolic name defined in the <sys/socket.h> header file. The defined families are as follows:

AF_INET
specifies ARPA Internet protocols.

AF_UNIX
specifies UNIX domain protocols. (Only used with integrated sockets.)

type
specifies the semantics of communication, as defined in <sys/socket.h> . The defined types are as follows:

SOCK_STREAM
provides sequenced, reliable byte streams based on two-way connections. This type also supports out-of-band transmission mechanisms.

SOCK_DGRAM
supports datagrams, which are connectionless messages of a fixed maximum length. The delivery of datagrams is unreliable. The application is responsible for acknowledgment and sequencing.

SOCK_RAW
provides access to low-level network protocols and interfaces.

A stream socket must be connected to another socket with a connect call before any data can be sent or received on it. Data are transferred using read or write calls or variants of the send and receive calls. The socket can be closed with a close call when the session is completed, or the socket will be closed automatically at program exit.

protocol
specifies the protocol to be used. If protocol is set to 0 , the system selects the default protocol number for the socket domain and type specified. This is usually adequate, since the most common socket types support only one protocol. getprotobyname and related calls can also be used to select the protocol.


RETURN VALUE

If socket is successful, it returns a descriptor referencing the socket; otherwise, it returns a -1 , and sets errno to indicate the type of error.


PORTABILITY

socket is portable to other environments, including most UNIX systems, that implement BSD sockets.


EXAMPLE

The following is an example of a complete socket program.

/* This is an example of a complete socket program. It is a      */
/* client program for the finger server which runs on many UNIX  */
/* systems. This client program returns information about logged */
/* on users for any remote system that is running the finger     */
/* server. The format of the command is:                         */          */       */
/*                                                               */
/*        finger [-l] hostname                                   */
/*                                                               */
/* The output is typically identical to that which one would     */
/* receive when running the "finger" command locally on that     */
/* system. Specification of the -l option results in more        */
/* verbose output.                                               */

#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <stdio.h>
#include <string.h>
#include <fcntl.h>

   /* No need to translate characters on ASCII systems.          */
#ifndef  __SASC__
#define ntohcs(c) (c)
#define htoncs(c) (c)
#endif

   /* Define some useful constants.                              */
#define FALSE 0
#define TRUE 1
#define READ_BLOCK_SIZE 256
#define OUTBUF_SIZE 2
#define FINGER_PORT 79
#define ASCII_CR 0x0D
#define ASCII_LF 0x0A
main(int argc, char *argv[])
{
   int n,i;

   /* Socket descriptor for communication with the finger server.*/
   int s;

   /* Socket address for server.                                 */
   struct sockaddr_in sa;

     /* Use to send ASCII CR and LF characters required by       */
     /* the protocol.                                            */
   char cr = ASCII_CR, lf = ASCII_LF;

     /* buffers  */
   char in[READ_BLOCK_SIZE] ;
   char out[OUTBUF_SIZE] ;

     /* option status  */
   int longlist = FALSE;
   char *op;

     /* will contain information about the finger service        */
   struct servent *serv;

     /* will contain information about the remote host           */
   struct hostent *host;

   if (*++argv && *argv[0] == '-') {     /* argument processing */
      op = *argv;
      if (op[1] == 'l' || op[1] == 'L')
         longlist = 1;
      else
          printf("finger: unsupported option  "%c"",op[1])
      argv++;
   }
   if (!*argv) {
      printf("finger: hostname missing");
      exit(EXIT_FAILURE);
   }

      /* Assume *argv now points to hostname.                     */
      /* Find the IP address for the requested host.              */
   host = gethostbyname(*argv);
   if (host==NULL) {
       printf("finger: Host %s is unknown.\n",*argv );
       exit(EXIT_FAILURE);
   }
      /* Find the port for the finger service. If the services file */
      /* is not available, we will use the standard number. We      */
      /* specify "tcp" as the protocol. This call attempts to       */
      /* find the services file.                                    */
   serv = getservbyname("finger", "tcp");

      /* Prepare a socket address for the server. We need an IP     */
      /* address(corresponding to the given host name) and a port   */
      /* number (corresponding to the "finger" service).         */
   memset(&sa,'\0',sizeof(sa));
   sa.sin_family = AF_INET;
   memcpy(&sa.sin_addr,host->h_addr,sizeof(sa.sin_addr));
   sa.sin_port = serv ? serv->s_port : htons(FINGER_PORT);

      /* Get a socket of the proper type. We use SOCK_STREAM     */
      /* because we want to communicate using TCP (we want  a    */
      /* reliable protocol).                                                 */
   s = socket(AF_INET, SOCK_STREAM, 0);
   if (s == -1) {
      perror("finger - socket() failed");
      exit(EXIT_FAILURE);
   }

      /* Connect to the host and port.                           */
   if (connect(s, &sa, sizeof(sa)) == -1) {
      perror("finger - connect() failed");
      return(EXIT_FAILURE);
   }

      /* read() and write() are the most convenient calls  for   */
      /* transmitting and receiving data over stream sockets.    */

      /* Write to server.                                        */
      /* If long option is specified, pass that first.           */
   if (longlist) {
      out[0]  = htoncs('/');
      out[1]  = htoncs('W');
      write(s,out,2);
   }
      /* Terminate msg with CR-LF. */
   write(s,&cr,1);
   write(s,&lf,1);
      /* Server should respond.    */
      /* Read until EOF indicated. */
   while (n=read(s,in,READ_BLOCK_SIZE)) {
      for (i=0; i<n ; i++) {
         if (in[i] ==ASCII_CR) continue;
            /* Presume part of CR-LF pair.                       */
         putchar(ntohcs(in[i] ));
      }
   }

      /* Close the socket.         */
   close(s);

}


RELATED FUNCTIONS

accept , bind , close connect , getsockname , getsockopt , givesocket , listen , open , read , recv , recvfrom , recvmsg , select , send , sendmsg , sendto , setsockopt , shutdown , takesocket , write , writev


Chapter Contents

Previous

Next

Top of Page

Copyright © 2001 by SAS Institute Inc., Cary, NC, USA. All rights reserved.