Tuesday, February 17, 2009

connect

#define  SA struct sockaddr

if (connect(sockfd, (SA *) &servaddr, sizeof(servaddr)) < 0)
    err_sys("connect error");

The connect function, when applied to a TCP socket, establishes a TCP connection with the server specified by the socket address structure pointed to by the second argument. We must also specify the length of the socket address structure as the third argument to connect, and for Internet socket address structures, we always let the compiler calculate the length using C's sizeof operator.

Everytime one of the socket functions requires a pointer to a socket address structure, that pointer must be cast to a pointer to a generic socket address structure(SA *). This is because the socket functions predate the ANSI C standard, so the void * pointer type was not available in the early 1980s when these functions were developed. The problem is that "struct sockaddr" is 15 characters and often causes the source code line to extend past the right edge of the screen (or page, in the case of a book), so we shorten it to SA.

2 comments:

Anonymous said...

thank you for your grate explanation in overall Socket programming.it'll more helpful to my exam...thanks

Anonymous said...

I'm university student from sri lanka.I confused this subject...Fortunatel before the date of my Exam I found your website.It's amazing... simple explanation goes there..excellent...i introduce your web sites to my other collegues... but for the Final exam..mid exam is over now :)

CJ from Sri Lanka