connect Function

43 篇文章 0 订阅

connect Function

The connect function establishes a connection to a specified socket.

int connect(
  __in          SOCKET s,
  __in          const struct sockaddr* name,
  __in          int namelen
);
Parameters
s

Descriptor identifying an unconnected socket.

name

Name of the socket in the sockaddr structure to which the connection should be established.

namelen

Length of name, in bytes.

Return Value

If no error occurs, connect returns zero. Otherwise, it returns SOCKET_ERROR, and a specific error code can be retrieved by calling WSAGetLastError.

On a blocking socket, the return value indicates success or failure of the connection attempt.

With a nonblocking socket, the connection attempt cannot be completed immediately. In this case, connect will return SOCKET_ERROR, and WSAGetLastError will return WSAEWOULDBLOCK. In this case, there are three possible scenarios:

  • Use the select function to determine the completion of the connection request by checking to see if the socket is writeable.
  • If the application is using WSAAsyncSelect to indicate interest in connection events, then the application will receive an FD_CONNECT notification indicating that the connect operation is complete (successfully or not).
  • If the application is using WSAEventSelect to indicate interest in connection events, then the associated event object will be signaled indicating that the connect operation is complete (successfully or not).

Until the connection attempt completes on a nonblocking socket, all subsequent calls to connect on the same socket will fail with the error code WSAEALREADY, and WSAEISCONN when the connection completes successfully. Due to ambiguities in version 1.1 of the Windows Sockets specification, error codes returned from connect while a connection is already pending may vary among implementations. As a result, it is not recommended that applications use multiple calls to connect to detect connection completion. If they do, they must be prepared to handle WSAEINVAL and WSAEWOULDBLOCK error values the same way that they handle WSAEALREADY, to assure robust execution.

If the error code returned indicates the connection attempt failed (that is, WSAECONNREFUSED, WSAENETUNREACH, WSAETIMEDOUT) the application can call connect again for the same socket.

Error codeMeaning

WSANOTINITIALISED

A successful WSAStartup call must occur before using this function.

WSAENETDOWN

The network subsystem has failed.

WSAEADDRINUSE

The socket's local address is already in use and the socket was not marked to allow address reuse with SO_REUSEADDR. This error usually occurs when executing bind, but could be delayed until this function if the bind was to a partially wildcard address (involving ADDR_ANY) and if a specific address needs to be committed at the time of this function.

WSAEINTR

The blocking Windows Socket 1.1 call was canceled through WSACancelBlockingCall.

WSAEINPROGRESS

A blocking Windows Sockets 1.1 call is in progress, or the service provider is still processing a callback function.

WSAEALREADY

A nonblocking connect call is in progress on the specified socket.

Note  In order to preserve backward compatibility, this error is reported as WSAEINVAL to Windows Sockets 1.1 applications that link to either Winsock.dll or Wsock32.dll.

WSAEADDRNOTAVAIL

The remote address is not a valid address (such as ADDR_ANY).

WSAEAFNOSUPPORT

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

WSAECONNREFUSED

The attempt to connect was forcefully rejected.

WSAEFAULT

The name or the namelen parameter is not a valid part of the user address space, the namelen parameter is too small, or the name parameter contains incorrect address format for the associated address family.

WSAEINVAL

The parameter s is a listening socket.

WSAEISCONN

The socket is already connected (connection-oriented sockets only).

WSAENETUNREACH

The network cannot be reached from this host at this time.

WSAEHOSTUNREACH

A socket operation was attempted to an unreachable host.

WSAENOBUFS

No buffer space is available. The socket cannot be connected.

WSAENOTSOCK

The descriptor is not a socket.

WSAETIMEDOUT

Attempt to connect timed out without establishing a connection.

WSAEWOULDBLOCK

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

WSAEACCES

Attempt to connect datagram socket to broadcast address failed because setsockopt option SO_BROADCAST is not enabled.

Remarks

The connect function is used to create a connection to the specified destination. If socket s, is unbound, unique values are assigned to the local association by the system, and the socket is marked as bound.

For connection-oriented sockets (for example, type SOCK_STREAM), an active connection is initiated to the foreign host using name (an address in the namespace of the socket; for a detailed description, see bind and sockaddr).

Note  If a socket is opened, a setsockopt call is made, and then a sendto call is made, Windows Sockets performs an implicit bind function call.

When the socket call completes successfully, the socket is ready to send and receive data. If the address member of the structure specified by the name parameter is all zeroes, connect will return the error WSAEADDRNOTAVAIL. Any attempt to reconnect an active connection will fail with the error code WSAEISCONN.

For connection-oriented, nonblocking sockets, it is often not possible to complete the connection immediately. In such a case, this function returns the error WSAEWOULDBLOCK. However, the operation proceeds.

When the success or failure outcome becomes known, it may be reported in one of two ways, depending on how the client registers for notification.

  • If the client uses the select function, success is reported in the writefds set and failure is reported in the exceptfds set.
  • If the client uses the functions WSAAsyncSelect or WSAEventSelect, the notification is announced with FD_CONNECT and the error code associated with the FD_CONNECT indicates either success or a specific reason for failure.

For a connectionless socket (for example, type SOCK_DGRAM), the operation performed by connect is merely to establish a default destination address that can be used on subsequent send/ WSASend and recv/ WSARecv calls. Any datagrams received from an address other than the destination address specified will be discarded. If the address member of the structure specified by name is all zeroes, the socket will be disconnected. Then, the default remote address will be indeterminate, so send/ WSASend and recv/ WSARecv calls will return the error code WSAENOTCONN. However, sendto/ WSASendTo and recvfrom/ WSARecvFrom can still be used. The default destination can be changed by simply calling connect again, even if the socket is already connected. Any datagrams queued for receipt are discarded if name is different from the previous connect.

For connectionless sockets, name can indicate any valid address, including a broadcast address. However, to connect to a broadcast address, a socket must use setsockopt to enable the SO_BROADCAST option. Otherwise, connect will fail with the error code WSAEACCES.

When a connection between sockets is broken, the sockets should be discarded and recreated. When a problem develops on a connected socket, the application must discard and recreate the needed sockets in order to return to a stable point.

Example Code

The following example demonstrates the use of the connect function.

#include <stdio.h>
#include "winsock2.h"

void main() {
  //----------------------
  // Initialize Winsock
  WSADATA wsaData;
  int iResult = WSAStartup(MAKEWORD(2,2), &wsaData);
  if (iResult != NO_ERROR)
    printf("Error at WSAStartup()\n");

  //----------------------
  // Create a SOCKET for connecting to server
  SOCKET ConnectSocket;
  ConnectSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
  if (ConnectSocket == INVALID_SOCKET) {
    printf("Error at socket(): %ld\n", WSAGetLastError());
    WSACleanup();
    return;
  }

  //----------------------
  // The sockaddr_in structure specifies the address family,
  // IP address, and port of the server to be connected to.
  sockaddr_in clientService; 
  clientService.sin_family = AF_INET;
  clientService.sin_addr.s_addr = inet_addr( "127.0.0.1" );
  clientService.sin_port = htons( 27015 );

  //----------------------
  // Connect to server.
  if ( connect( ConnectSocket, (SOCKADDR*) &clientService, sizeof(clientService) ) == SOCKET_ERROR) {
    printf( "Failed to connect.\n" );
    WSACleanup();
    return;
  }

  printf("Connected to server.\n");
  WSACleanup();
  return;
}

For another example that uses the connect function, see Getting Started With Winsock.

Notes for IrDA Sockets

  • The Af_irda.h header file must be explicitly included.
  • If an existing IrDA connection is detected at the media-access level, WSAENETDOWN is returned.
  • If active connections to a device with a different address exist, WSAEADDRINUSE is returned.
  • If the socket is already connected or an exclusive/multiplexed mode change failed, WSAEISCONN is returned.
  • If the socket was previously bound to a local service name to accept incoming connections using bind, WSAEINVAL is returned. Note that once a socket is bound, it cannot be used for establishing an outbound connection.

IrDA implements the connect function with addresses of the form sockaddr_irda. Typically, a client application will create a socket with the socket function, scan the immediate vicinity for IrDA devices with the IRLMP_ENUMDEVICES socket option, choose a device from the returned list, form an address, and then call connect. There is no difference between blocking and nonblocking semantics.

Requirements

Client

Requires Windows Vista, Windows XP, Windows 2000 Professional, Windows NT Workstation, Windows Me, Windows 98, or Windows 95.

Server

Requires Windows Server 2008, Windows Server 2003, Windows 2000 Server, or Windows NT Server.

Header

Declared in Winsock2.h.

Library

Use Ws2_32.lib.

DLL

Requires Ws2_32.dll.

See Also

Winsock Reference
Winsock Functions
accept
bind
getsockname
select
sockaddr
socket
WSAAsyncSelect
WSAConnect


Send comments about this topic to Microsoft

Build date: 8/15/2007

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
"No matching function for call to 'connect'" 这个错误通常出现在Qt的connect函数调用时,意味着在调用connect函数时,没有找到匹配的函数。根据引用,connect函数有多个重载版本,每个版本都有不同的参数类型和数量。为了正确调用connect函数,参数类型和数量必须与可用的重载版本匹配。根据引用和引用,错误的原因可能是connect函数的参数类型或数量与可用的重载版本不匹配。为了解决这个问题,你可以检查参数类型、数量和顺序是否正确,并确保调用的版本与你期望的版本匹配。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *3* [Qt:no matching function for call to (类名)::connect()的错误原因总结](https://blog.csdn.net/tjcwt2011/article/details/110297280)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] - *2* [QT使用信号与槽时编译错误“no matching function for call to connect](https://blog.csdn.net/qq_41854911/article/details/128059174)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值