connect function (winsock)
Establishes a connection to a specified socket.
Syntax
int connect(
SOCKET s,
const struct sockaddr *name,
int namelen
);
Parameters
Parameter | Description |
---|---|
s | Descriptor identifying the socket to be connected. |
name | Pointer to a sockaddr structure that contains the address of the target socket. |
namelen | Length, in bytes, of the address pointed to by name . |
Return Value
If the function succeeds, 0
is returned. On error, -1
is returned and WSAGetLastError()
provides extended error information.
Remarks
The connect
function is used by a client socket to establish a connection to a server socket. For connection-oriented protocols (e.g., TCP), this initiates the three-way handshake. For connectionless protocols (e.g., UDP), connect
merely sets a default remote address for subsequent send
and recv
calls.
Example
See Also
Example: Connecting to a TCP server
#include <winsock2.h>
#include <ws2tcpip.h>
#pragma comment(lib, "Ws2_32.lib")
int main() {
WSADATA wsaData;
SOCKET ConnectSocket = INVALID_SOCKET;
struct addrinfo *result = NULL, hints;
const char *sendbuf = "Hello, Server!";
char recvbuf[512];
int iResult, recvbuflen = sizeof(recvbuf);
WSAStartup(MAKEWORD(2,2), &wsaData);
ZeroMemory(&hints, sizeof(hints));
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
hints.ai_protocol = IPPROTO_TCP;
getaddrinfo("example.com", "80", &hints, &result);
ConnectSocket = socket(result->ai_family, result->ai_socktype, result->ai_protocol);
connect(ConnectSocket, result->ai_addr, (int)result->ai_addrlen);
iResult = send(ConnectSocket, sendbuf, (int)strlen(sendbuf), 0);
iResult = recv(ConnectSocket, recvbuf, recvbuflen, 0);
closesocket(ConnectSocket);
WSACleanup();
return 0;
}