تابع ()connect

در client ، بعد از فراخوانی تابع ()socket از تابع ()connect برای ایجاد اتصال به server استفاده می کنیم. سیستم عامل اتوماتیک یک پورت بزرگتر از 1024 را به عنوان source port برای ارتباط با server اختصاص خواهد داد:

// man 2 connect
#include <sys/types.h>
#include <sys/socket.h>
 
int connect(int sockfd, const struct sockaddr *addr, socklen_t addrlen);

مثال

#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
 
#define handle_error(msg) \
		do { perror(msg); exit(EXIT_FAILURE); } while(0)
 
#define SERVER	"127.0.0.1"
#define PORT	"9530"
 
int main()
{
	int status, sockfd;
	struct addrinfo hints, *res, *rp;
 
	memset(&hints, 0, sizeof(hints));
	hints.ai_family = AF_UNSPEC;
	hints.ai_socktype = SOCK_STREAM;
	hints.ai_protocol = 0;
 
	status = getaddrinfo(SERVER, PORT, &hints, &res);
	if (status != 0) {
		fprintf(stderr, "getaddrinfo() error: %s\n", gai_strerror(status));
		exit(EXIT_FAILURE);
	}
 
	for (rp = res; rp != NULL; rp = rp->ai_next) {
		sockfd = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
		if (sockfd == -1) {
			handle_error("socket() error");
			continue;
		}
 
		status = connect(sockfd, rp->ai_addr, rp->ai_addrlen);
		if (status == 0)
			break;
 
		handle_error("bind() error");
		close(sockfd);
	}
	freeaddrinfo(res);
 
	if (rp == NULL) {
		fprintf(stdout, "No connection made\n");
	} else {
		fprintf(stdout, "I got connected\n");
		close(sockfd);
	}
 
	return 0;
}

خروجی

bind() error: Connection refused