Taken from the original at http://www.ecst.csuchico.edu/~beej/guide/net/ ... see end of writeup for Copyright statement.

connect()--Hey, you!

Let's just pretend for a few minutes that you're a telnet application. Your user commands you (just like in the movie TRON) to get a socket file descriptor. You comply and call socket(). Next, the user tells you to connect to "" on port "23" (the standard telnet port.) Oh my God! What do you do now?

Lucky for you, program, you're now perusing the section on connect() -- how to connect to a remote host. You read furiously onward, not wanting to disappoint your user...

The connect() call is as follows:

#include <sys/types.h>
#include <sys/socket.h>

int connect(int sockfd, struct sockaddr *serv_addr, int addrlen);

sockfd is our friendly neighborhood socket file descriptor, as returned by the socket() call, serv_addr is a struct sockaddr containing the destination port and IP address, and addrlen can be set to sizeof(struct sockaddr).

Isn't this starting to make more sense? Let's have an example:

#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>

#define DEST_IP   ""
#define DEST_PORT 23

  int sockfd;
  struct sockaddr_in dest_addr;   /* will hold the destination addr */

  sockfd = socket(AF_INET, SOCK_STREAM, 0); /* do some error checking! */

  dest_addr.sin_family = AF_INET;        /* host byte order */
  dest_addr.sin_port = htons(DEST_PORT); /* short, network byte order */
  dest_addr.sin_addr.s_addr = inet_addr(DEST_IP);
  bzero(&(dest_addr.sin_zero), 8);       /* zero the rest of the struct */

  /* don't forget to error check the connect()! */
  connect(sockfd, (struct sockaddr *)&dest_addr, sizeof(struct sockaddr));

Again, be sure to check the return value from connect()--it'll return -1 on error and set the variable errno.

Also, notice that we didn't call bind(). Basically, we don't care about our local port number; we only care where we're going. The kernel will choose a local port for us, and the site we connect to will automatically get this information from us. No worries.

Prev | Up | Next

Copyright © 1995, 1996 by Brian "Beej" Hall. This guide may be reprinted in any medium provided that its content is not altered, it is presented in its entirety, and this copyright notice remains intact. Contact beej@ecst.csuchico.edu for more information.

Log in or register to write something here or to contact authors.