--#-- You'll only do this once --#-- Having wrestled the Internet address out of the host string and set up the Internet socket address structure, opening and connecting to the socket is quite straightforward.

// NOW open the socket if ((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0) die("Can't open socket\n"); // And connect if (connect (sock, &sockInfo, sizeof(sockInfo)) == -1) die("Cannot connect to socket\n");
The int sock returned by the call to socket() acts very much like a file handle. You can write to and read from it and even close it when you're done.

int writeToSocket(int sock, char *request) { int bytesWritten; bytesWritten = write (sock, request, strlen(request)); return bytesWritten; }
For the sake of this exercise, we'll immediately print anything the server sends on stdout.

// helper function to get the bytes off the socket int readn(int sock, char *buf,int readSize) { unsigned char *p; int i; int numRead; p = (unsigned char *)buf; i = 0; while(i < readSize) { numRead = read(sock, p, readSize - i); if (numRead <= 0) return(i); p += numRead; i += numRead; } return(i); } // public function we'll call void printServerResponse(int sock) { int bytesRead; int readSize = 4096; char buf[readSize + 2]; memset (buf, 0, sizeof(buf)); while (bytesRead = readn(sock, buf, readSize)) { printf(buf); memset (buf, 0, sizeof(buf)); } close (sock); }
Now, put this all in a file called sockets.c and see if it compiles on your system. (If it doesn't, let me hear about it. And if you don't fully understand all this, don't worry too much about it. Once you get it working, you may never have to touch it again. I used similar code for well over a year before trying to figure out how it worked.