1 CONNECT(3C)              Standard C Library Functions              CONNECT(3C)
   2 
   3 NAME
   4      connect - initiate a connection on a socket
   5 
   6 LIBRARY
   7      Standard C Library (libc, -lc)
   8 
   9 SYNOPSIS
  10      #include <sys/types.h>
  11      #include <sys/socket.h>
  12 
  13      int
  14      connect(int s, const struct sockaddr *name, socklen_t namelen);
  15 
  16 DESCRIPTION
  17      The parameter s is a socket.  If it is of type SOCK_DGRAM, connect()
  18      specifies the peer with which the socket is to be associated.  This
  19      address is the address to which datagrams are to be sent if a receiver is
  20      not explicitly designated.  This address is the only address from which
  21      datagrams are to be received.  If the socket s is of type SOCK_STREAM,
  22      connect() attempts to make a connection to another socket.  The other
  23      socket is specified by name.  name is an address in the communication
  24      space of the socket.  Each communication space interprets the name
  25      parameter in its own way.  If s is not bound, then s will be bound to an
  26      address selected by the underlying transport provider.  Generally, stream
  27      sockets can successfully connect() only once.  Datagram sockets can use
  28      connect() multiple times to change their association.  Datagram sockets
  29      can dissolve the association by connecting to a null address.
  30 
  31    Non-blocking Sockets
  32      When a socket is created, it is by default a blocking socket.  A socket
  33      may be configured to be non-blocking either at socket creation time or
  34      through the use of fcntl(2).  When a socket is set to be non-blocking, a
  35      call to connect() initiates an asynchronous connection.  If the
  36      connection cannot be completed without blocking, such as when making a
  37      TCP connection to a remote server, then  the connection attempt is made
  38      in the background and connect() returns -1 and errno is set to
  39      EINPROGRESS.
  40 
  41      Applications can obtain the state of this connection attempt by polling
  42      the socket's file descriptor for POLLOUT.  The event ports facility is
  43      the preferred means of polling on the file descriptor, see
  44      port_create(3C) and port_get(3C) for more information on event ports;
  45      however, applications may also use traditional portable routines like
  46      poll(2) and select(3C).
  47 
  48      When an asynchronous connection has completed, the application must call
  49      getsockopt(3C) using the macro SOL_SOCKET as the level argument and the
  50      macro SO_ERROR as the value of the option argument.  If the value of the
  51      SO_ERROR socket option is zero, then the connect was successfully
  52      established.  Otherwise, the connection could not be established and the
  53      value is the corresponding error code that would be commonly found in
  54      errno.
  55 
  56      Even when a socket is in non-blocking mode, a call to connect() may fail
  57      synchronously.  If any error other than EINPROGRESS or EINTR occurs, then
  58      there is no need for the application to poll for asynchronous completion.
  59      Similarly, if a call to connect() returns successfully, then the socket
  60      connection will be established and there is no need to poll for
  61      completion.
  62 
  63 RETURN VALUES
  64      If the connection or binding succeeds, 0 is returned.  Otherwise, -1 is
  65      returned and sets errno to indicate the error.
  66 
  67 EXAMPLES
  68      Example 1 Performing an asynchronous connection
  69              The following sample C program shows how to create and connect to
  70              a remote host using TCP.
  71 
  72              #include <sys/types.h>
  73              #include <sys/socket.h>
  74              #include <netinet/in.h>
  75              #include <arpa/inet.h>
  76              #include <inttypes.h>
  77              #include <stdio.h>
  78              #include <strings.h>
  79              #include <stdlib.h>
  80              #include <errno.h>
  81              #include <port.h>
  82              #include <unistd.h>
  83              #include <assert.h>
  84 
  85              int
  86              main(int argc, char *argv[])
  87              {
  88                      char *eptr;
  89                      long port;
  90                      int sock, ret, eport;
  91                      struct sockaddr_in6 sin6;
  92 
  93                      if (argc != 3) {
  94                              fprintf(stderr, "connect: <IP> <port>\n");
  95                              return (1);
  96                      }
  97 
  98                      bzero(&sin6, sizeof (struct sockaddr_in6));
  99                      sin6.sin6_family = AF_INET6;
 100 
 101                      /*
 102                       * Try to parse as an IPv6 address and then try v4.
 103                       */
 104                      ret = inet_pton(AF_INET6, argv[1], &sin6.sin6_addr);
 105                      if (ret == -1) {
 106                              perror("inet_pton");
 107                              return (1);
 108                      } else if (ret == 0) {
 109                              struct in_addr v4;
 110                              ret = inet_pton(AF_INET, argv[1], &v4);
 111                              if (ret == -1) {
 112                                      perror("inet_pton");
 113                                      return (1);
 114                              } else if (ret == 0) {
 115                                      fprintf(stderr, "connect: %s is not a valid "
 116                                          "IPv4 or IPv6 address\n", argv[1]);
 117                                      return (1);
 118                              }
 119                              /* N.B. Not a portable macro */
 120                              IN6_INADDR_TO_V4MAPPED(&v4, &sin6.sin6_addr);
 121                      }
 122 
 123                      errno = 0;
 124                      port = strtol(argv[2], &eptr, 10);
 125                      if (errno != 0 || *eptr != '\0') {
 126                              fprintf(stderr, "failed to parse port %s\n", argv[2]);
 127                              return (1);
 128                      }
 129                      if (port <= 0 || port > UINT16_MAX) {
 130                              fprintf(stderr, "invalid port: %ld\n", port);
 131                              return (1);
 132                      }
 133                      sin6.sin6_port = htons(port);
 134 
 135                      sock = socket(AF_INET6, SOCK_STREAM | SOCK_NONBLOCK, 0);
 136                      if (sock <      0) {
 137                              perror("socket");
 138                              return (1);
 139                      }
 140 
 141                      eport = port_create();
 142                      if (eport < 0) {
 143                              perror("port_create");
 144                              (void) close(sock);
 145                              return (1);
 146                      }
 147 
 148                      ret = connect(sock, (struct sockaddr *)&sin6,
 149                          sizeof (struct sockaddr_in6));
 150                      if (ret != 0 && errno != EINPROGRESS && errno != EINTR) {
 151                              perror("connect");
 152                              (void) close(sock);
 153                              (void) close(eport);
 154                              return (1);
 155                      }
 156 
 157                      if (ret != 0) {
 158                              port_event_t pe;
 159                              int err;
 160                              socklen_t sz = sizeof (err);
 161                              if (port_associate(eport, PORT_SOURCE_FD, sock, POLLOUT,
 162                                  NULL) != 0) {
 163                                      perror("port_associate");
 164                                      (void) close(sock);
 165                                      (void) close(eport);
 166                                      return (1);
 167                              }
 168                              if (port_get(eport, &pe, NULL) != 0) {
 169                                      perror("port_get");
 170                                      (void) close(sock);
 171                                      (void) close(eport);
 172                                      return (1);
 173                              }
 174                              assert(pe.portev_source == PORT_SOURCE_FD);
 175                              assert(pe.portev_object == (uintptr_t)sock);
 176                              if (getsockopt(sock, SOL_SOCKET, SO_ERROR, &err, &sz) != 0) {
 177                                      perror("getsockopt");
 178                                      (void) close(sock);
 179                                      (void) close(eport);
 180                                      return (1);
 181                              }
 182                              if (err != 0) {
 183                                      /* Asynch connect failed */
 184                                      fprintf(stderr, "asnchronous connect: %s\n",
 185                                          strerror(err));
 186                                      (void) close(sock);
 187                                      (void) close(eport);
 188                                      return (1);
 189                              }
 190                      }
 191 
 192                      /* Read and write to the socket and then clean up */
 193 
 194                      return (0);
 195              }
 196 
 197 ERRORS
 198      The call fails if:
 199 
 200      [EACCES]           Search permission is denied for a component of the
 201                         path prefix of the pathname in name.
 202 
 203      [EADDRINUSE]       The address is already in use.
 204 
 205      [EADDRNOTAVAIL]    The specified address is not available on the remote
 206                         machine.
 207 
 208      [EAFNOSUPPORT]     Addresses in the specified address family cannot be
 209                         used with this socket.
 210 
 211      [EALREADY]         The socket is non-blocking,  and a previous connection
 212                         attempt has not yet been completed.
 213 
 214      [EBADF]            s is not a valid descriptor.
 215 
 216      [ECONNREFUSED]     The attempt to connect was forcefully rejected.  The
 217                         calling program should close(2) the socket descriptor,
 218                         and issue another socket(3C) call to obtain a new
 219                         descriptor before attempting another connect() call.
 220 
 221      [EINPROGRESS]      The socket is non-blocking, and the connection cannot
 222                         be completed immediately.  See the section on Non-
 223                         blocking Sockets for more information.
 224 
 225      [EINTR]            The connection attempt was interrupted before any data
 226                         arrived by the delivery of a signal.  The connection,
 227                         however, will be established asynchronously.
 228 
 229      [EINVAL]           namelen is not the size of a valid address for the
 230                         specified address family.
 231 
 232      [EIO]              An I/O error occurred while reading from or writing to
 233                         the file system.
 234 
 235      [EISCONN]          The socket is already connected.
 236 
 237      [ELOOP]            Too many symbolic links were encountered in
 238                         translating the pathname in name.
 239 
 240      [ENETUNREACH]      The network is not reachable from this host.
 241 
 242      [EHOSTUNREACH]     The remote host is not reachable from this host.
 243 
 244      [ENOENT]           A component of the path prefix of the pathname in name
 245                         does not exist.
 246 
 247                         The socket referred to by the pathname in name does
 248                         not exist.
 249 
 250      [ENOSR]            There were insufficient STREAMS resources available to
 251                         complete the operation.
 252 
 253      [ENXIO]            The server exited before the connection was complete.
 254 
 255      [ETIMEDOUT]        Connection establishment timed out without
 256                         establishing a connection.
 257 
 258      [EWOULDBLOCK]      The socket is marked as non-blocking, and the
 259                         requested operation would block.
 260 
 261      The following errors are specific to connecting names in the UNIX domain.
 262      These errors might not apply in future versions of the UNIX IPC domain.
 263 
 264      [ENOTDIR]          A component of the path prefix of the pathname in name
 265                         is not a directory.
 266 
 267      [ENOTSOCK]         s is not a socket.
 268 
 269      [EPROTOTYPE]       The file that is referred to by name is a socket of a
 270                         type other than type s.  For example, s is a
 271                         SOCK_DGRAM socket, while name refers to a SOCK_STREAM
 272                         socket.
 273 
 274 MT-LEVEL
 275      Safe
 276 
 277 SEE ALSO
 278      close(2), accept(3C), getsockname(3C), select(3C), sockaddr(3C),
 279      socket(3C), socket.h(3HEAD), attributes(5)
 280 
 281 illumos                         August 2, 2018                         illumos