Establishes a connection to a specified remote server.
int connect(
SOCKET s,
const sockaddr *connectdata,
int namelen
);
The connect function establishes a connection to a server application on the specified remote host. The socket s must be of type SOCK_STREAM or SOCK_DGRAM.
For a connection-oriented socket (like SOCK_STREAM), the connectdata parameter points to a sockaddr_in structure that specifies the destination address and port. The function initiates a connection to the specified destination.
For a connectionless socket (like SOCK_DGRAM), connect can be used to establish a default destination for subsequent datagrams. This is useful for simplifying datagram sending and receiving.
A simple example of using the connect function:
#include <winsock2.h>
#include <ws2tcpip.h>
#include <iostream>
// Link with Ws2_32.lib
#pragma comment(lib, "Ws2_32.lib")
int main() {
WSADATA wsaData;
int iResult;
SOCKET ConnectSocket = INVALID_SOCKET;
struct sockaddr_in clientService;
// Initialize Winsock
iResult = WSAStartup(MAKEWORD(2,2), &wsaData);
if (iResult != 0) {
std::cerr << "WSAStartup failed: " << iResult << std::endl;
return 1;
}
// Create a SOCKET for connecting to server
ConnectSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (ConnectSocket == INVALID_SOCKET) {
std::cerr << "socket failed: " << WSAGetLastError() << std::endl;
WSACleanup();
return 1;
}
//----------------------
// Connect to server
//----------------------
clientService.sin_family = AF_INET;
clientService.sin_addr.s_addr = inet_addr("127.0.0.1"); // Replace with server IP
clientService.sin_port = htons(80); // Replace with server port
iResult = connect(ConnectSocket, (SOCKADDR *) &clientService, sizeof(clientService));
if (iResult == SOCKET_ERROR) {
std::cerr << "connect failed: " << WSAGetLastError() << std::endl;
closesocket(ConnectSocket);
WSACleanup();
return 1;
}
std::cout << "Connected to server!" << std::endl;
// ... send and receive data ...
// cleanup
closesocket(ConnectSocket);
WSACleanup();
return 0;
}