Connect function in linux

connect(3) — Linux man page

This manual page is part of the POSIX Programmer’s Manual. The Linux implementation of this interface may differ (consult the corresponding Linux manual page for details of Linux behavior), or the interface may not be implemented on Linux.

Name

Synopsis

int connect(int socket, const struct sockaddr *address,
socklen_t address_len);

Description

The connect() function shall attempt to make a connection on a socket. The function takes the following arguments: socket Specifies the file descriptor associated with the socket. address Points to a sockaddr structure containing the peer address. The length and format of the address depend on the address family of the socket. address_len Specifies the length of the sockaddr structure pointed to by the address argument.

If the socket has not already been bound to a local address, connect() shall bind it to an address which, unless the socket’s address family is AF_UNIX, is an unused local address.

If the initiating socket is not connection-mode, then connect() shall set the socket’s peer address, and no connection is made. For SOCK_DGRAM sockets, the peer address identifies where all datagrams are sent on subsequent send() functions, and limits the remote sender for subsequent recv() functions. If address is a null address for the protocol, the socket’s peer address shall be reset.

If the initiating socket is connection-mode, then connect() shall attempt to establish a connection to the address specified by the address argument. If the connection cannot be established immediately and O_NONBLOCK is not set for the file descriptor for the socket, connect() shall block for up to an unspecified timeout interval until the connection is established. If the timeout interval expires before the connection is established, connect() shall fail and the connection attempt shall be aborted. If connect() is interrupted by a signal that is caught while blocked waiting to establish a connection, connect() shall fail and set errno to [EINTR], but the connection request shall not be aborted, and the connection shall be established asynchronously.

Читайте также:  Как установить forticlient на linux

If the connection cannot be established immediately and O_NONBLOCK is set for the file descriptor for the socket, connect() shall fail and set errno to [EINPROGRESS], but the connection request shall not be aborted, and the connection shall be established asynchronously. Subsequent calls to connect() for the same socket, before the connection is established, shall fail and set errno to [EALREADY].

When the connection has been established asynchronously, select() and poll() shall indicate that the file descriptor for the socket is ready for writing.

The socket in use may require the process to have appropriate privileges to use the connect() function.

Return Value

Upon successful completion, connect() shall return 0; otherwise, -1 shall be returned and errno set to indicate the error.

Errors

The connect() function shall fail if: EADDRNOTAVAIL The specified address is not available from the local machine. EAFNOSUPPORT The specified address is not a valid address for the address family of the specified socket. EALREADY A connection request is already in progress for the specified socket. EBADF The socket argument is not a valid file descriptor. ECONNREFUSED The target address was not listening for connections or refused the connection request. EINPROGRESS O_NONBLOCK is set for the file descriptor for the socket and the connection cannot be immediately established; the connection shall be established asynchronously. EINTR The attempt to establish a connection was interrupted by delivery of a signal that was caught; the connection shall be established asynchronously. EISCONN The specified socket is connection-mode and is already connected. ENETUNREACH No route to the network is present. ENOTSOCK The socket argument does not refer to a socket. EPROTOTYPE The specified address has a different type than the socket bound to the specified peer address. ETIMEDOUT The attempt to connect timed out before a connection was made.

If the address family of the socket is AF_UNIX, then connect() shall fail if: EIO An I/O error occurred while reading from or writing to the file system. ELOOP A loop exists in symbolic links encountered during resolution of the pathname in address. ENAMETOOLONG A component of a pathname exceeded characters, or an entire pathname exceeded characters. ENOENT A component of the pathname does not name an existing file or the pathname is an empty string. ENOTDIR A component of the path prefix of the pathname in address is not a directory.

Читайте также:  Linux mint mediatek mt7630e

The connect() function may fail if: EACCES Search permission is denied for a component of the path prefix; or write access to the named socket is denied. EADDRINUSE Attempt to establish a connection that uses addresses that are already in use. ECONNRESET Remote host reset the connection request. EHOSTUNREACH The destination host cannot be reached (probably because the host is down or a remote router cannot reach it). EINVAL The address_len argument is not a valid length for the address family; or invalid address family in the sockaddr structure. ELOOP More than symbolic links were encountered during resolution of the pathname in address. ENAMETOOLONG Pathname resolution of a symbolic link produced an intermediate result whose length exceeds . ENETDOWN The local network interface used to reach the destination is down. ENOBUFS No buffer space is available. EOPNOTSUPP The socket is listening and cannot be connected.

The following sections are informative.

Examples

Application Usage

If connect() fails, the state of the socket is unspecified. Conforming applications should close the file descriptor and create a new socket before attempting to reconnect.

Rationale

Future Directions

See Also

accept(), bind(), close(), getsockname(), poll(), select(), send(), shutdown(), socket(), the Base Definitions volume of IEEE Std 1003.1-2001,

Источник

Connect function in linux

int connect(int sockfd , const struct sockaddr * serv_addr , socklen_t addrlen );

ОПИСАНИЕ

Файловый дескриптор sockfd должен ссылаться на сокет. Если сокет имеет тип SOCK_DGRAM , значит, адрес serv_addr является адресом по умолчанию, куда посылаются датаграммы, и единственным адресом, откуда они принимаются. Если сокет имеет тип SOCK_STREAM или SOCK_SEQPACKET , то данный системный вызов попытается установить соединение с другим сокетом. Другой сокет задан параметром serv_addr , являющийся адресом длиной addrelen в пространстве коммуникации сокета. Каждое пространство коммуникации интерпретирует параметр serv_addr по-своему.

Обычно сокеты с протоколами, основанными на соединении, могут устанавливать соединение только один раз; сокеты с протоколами без соединения могут использовать connect многократно, чтобы изменить адрес назначения. Сокеты без поддержки соединения могут прекратить связь с другим сокетом, установив член sa_family структуры sockaddr в AF_UNSPEC .

Читайте также:  Was admin console linux

ВОЗВРАЩАЕМОЕ ЗНАЧЕНИЕ

Если соединение или привязка прошла успешно, возвращается нуль. При ошибке возвращается -1, а errno устанавливается должным образом.

ОШИБКИ

Ниже следуют только общие ошибки сокетов. Могут также появляться коды ошибок, существующие в конкретном домене. EBADF Файловый дескриптор не является правильными индексом в таблице дескрипторов. EFAULT Адрес структуры сокета находится за пределами адресного пространства пользователя. ENOTSOCK Файловый дескриптор не связан с сокетом. EISCONN Соединение на сокете уже произошло. ECONNREFUSED С той стороны никто не слушает. ETIMEDOUT Произошел тайм-аут во время ожидания соединения. Сервер, возможно, очень занят и не может принимать новые соединения. Заметьте, что для IP-сокетов тайм-аут может быть очень длинным, если на сервере разрешено использование syncookies. ENETUNREACH Сеть недоступна. EADDRINUSE Локальный адрес уже используется. EINPROGRESS Сокет является неблокирующим, а соединение не может быть установлено прямо сейчас. Можно использовать select (2) или poll (2), чтобы закончить соединение, установив ожидание возможности записи в сокет. После того, как select сообщит о такой возможности, используйте getsockopt (2), чтобы прочитать флаг SO_ERROR на уровне SOL_SOCKET , чтобы определить, успешно ли завершился connect (в этом случае SO_ERROR равен нулю) или неуспешно, тогда SO_ERROR равен одному из обычных кодов ошибок, перечисленных здесь, и объясняет причину неудачи). EALREADY Сокет является неблокирующим, а предыдущая попытка установить соединение еще не завершилась. EAGAIN Не осталось свободных локальных портов, или же недостаточно места в кэше маршрутизации. Для домена PF_INET смотри описание системной переменной net.ipv4.ip_local_port_range в ip (7), где описано, как увеличить количество локальных портов. EAFNOSUPPORT Адрес имеет некорректную семью адресов в поле sa_family . EACCES, EPERM Пользователь попытался соединиться с широковещательным адресом, не установив широковещательный флаг на сокете или же запрос на соединение завершился неуспешно из-за локального правила на файерволле.

СООТВЕТСТВИЕ СТАНДАРТАМ

SVr4, 4.4BSD (функция connect впервые появилась в BSD 4.2). SVr4 документирует дополнительные общие коды ошибок EADDRNOTAVAIL , EINVAL , EAFNOSUPPORT , EALREADY , EINTR , EPROTOTYPE , и ENOSR . Там также документируется множество дополнительных кодов ошибок, не описанных здесь.

ЗАМЕЧАНИЕ

Третий аргумент connect в действительности имеет тип int (а в BSD 4.*, libc4 и libc5 это так и есть). Определенное недопонимание привело к появлению socklen_t . Черновик стандарта еще не принят, но glibc2 уже следует ему и в ней присутствует socklen_t . Смотри также accept (2).

Источник

Оцените статью
Adblock
detector