connect |
Prototype: |
#include <sys/socket.h>
#include <resolv.h>
int connect(int sockfd, struct sockaddr *addr, int addr_len);
|
General Description: |
Connect to a peer or server. You may use this function for either SOCK_DGRAM or SOCK_STREAM protocols. For UDP, it merely remembers the port you connected to. This allows you to use send() and recv(). For TCP (SOCK_STREAM), this call starts the three-way handshake for stream communications. |
Return Value: |
Zero (0) if everything goes well. If an error occurs, you can find the cause in errno. |
Parameters |
sockfd |
The freshly created socket. You could optionally call bind() before this to assign the local port. If you do not the kernel assigns the next available port slot. |
addr |
The address and port of the destination address. |
addr_len |
The length of addr data block. |
Possible Errors |
EBADF |
Bad descriptor. |
EFAULT |
The socket structure address is outside the user's address space. This is caused by a bad addr structure reference. |
ENOTSOCK |
The descriptor is not associated with a socket. |
EISCONN |
The socket is already connected. You cannot reconnect a connected socket. Instead, you have to close the socket and create a new one. |
ECONNREFUSED |
Connection refused at server. |
ETIMEDOUT |
Timeout while attempting connection. |
ENETUNREACH |
Network is unreachable. |
EADDRINUSE |
Address is already in use. |
EINPROGRESS |
The socket is non-blocking and the connection cannot be completed immediately. It is possible to select() or poll() for completion by selecting the socket for writing. After select indicates writability, use getsockopt() to read the SO_ERROR option at level SOL_SOCKET to determine whether connect completed successfully (SO_ERROR is zero) or unsuccessfully (SO_ERROR is one of the usual error codes listed above, explaining the reason for the failure). |
EALREADY |
The socket is non-blocking and a previous connection attempt has not yet been completed. |
EAFNOSUPPORT |
The passed address didn't have the correct address family in its sa_family field. |
EACCES |
The user tried to connect to a broadcast address without having the socket broadcast flag enabled. |
Examples |
int sockfd;
struct sockaddr_in addr;
sockfd = socket(PF_INET, SOCK_STREAM, 0);
bzero(&addr, sizeof(addr));
addr.sin_family = AF_INET;
addr.sin_port = 13; /* current time */
inet_atoi("127.0.0.1", &addr.sin_addr);
if ( connect(sockfd, &addr, sizeof(addr)) != 0 )
perror("connect");
|