connect

Initiates a connection on a socket.

Library:LibC
Standard:ANSI
Service:Networking

Syntax

  #include <sys/socket.h> 
   
  int connect (
     int                     s,
     const struct sockaddr  *addr,
     size_t                  len);
  

Parameters

s

(IN) Specifies the socket file handle on which a connection is to be initiated.

addr

(IN) Points to the location of the address for the socket. The length and format of the address depend on the address family of the socket. For IPv4, addr should point to a sockaddr structure; for IPv6, to a sockaddr_in6 structure.

len

(IN) Specifies the amount of space pointed to by addr.

Return Values

If successful, returns 0. Otherwise, returns -1 and sets errno to one of the following:

Decimal

Constant

Description

4

EBADF

The socket parameter is not a valid socket file handle.

9

EINVAL

The length is invalid, or the socket has been reset and is no longer valid.

36

EINPROGRESS

The socket is nonblocking, and the connection cannot be completed immediately.

37

EALREADY

The socket is nonblocking, and a previous connection attempt has not yet been completed.

38

ENOTSOCK

The socket parameter is not a valid socket file handle.

42

ENOPROTOOPT

The option is unknown at the level indicated.

47

EAFNOSUPPORT

Addresses in the specified address family cannot be used with this socket.

48

EADDRINUSE

The address is already in use.

49

EADDRNOTAVAIL

The specified address is not available from the local computer.

51

ENETUNREACH

The network cannot be reached from this host.

56

EISCONN

The socket is already connected.

60

ETIMEDOUT

Connection timed out without establishing a connection.

61

ECONNREFUSED

The attempt to connect was forcefully rejected.

Remarks

If the socket is SOCK_DGRAM, connect specifies the peer (for example, a socket endpoint for either a client or a server) with which the socket is to be associated. Only the address of that socket endpoint receives or sends datagrams. SOCK_DGRAM sockets can call connect multiple times to change their association. Datagram sockets end the association by connecting to an invalid address, such as a NULL address.

If the socket is SOCK_STREAM, connect attempts to make a connection to another socket. Generally, SOCK_STREAM sockets can successfully connect to a peer once only.

If a SOCK_STREAM socket is in a blocking mode, connect blocks until a connection is established or the attempt fails. If the socket is set for nonblocking I/O, it returns an error code.

By selecting the socket for writing, you can also select it for completing the connection.