/* sockets.c */ // This code is provided "as is" with NO WARRANTY expressed or // implied. You may use it freely at your own risk. #include #include #include #include int writeToSocket(int sock, char *request) { int bytesWritten; bytesWritten = write (sock, request, strlen(request)); return bytesWritten; } 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); } 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); } int openSocket(char *host, int port) { long ipAddress; struct hostent* hostInfo; struct sockaddr_in sockInfo; int sock; memset(&sockInfo, 0, sizeof(sockInfo)); sockInfo.sin_family = AF_INET; sockInfo.sin_port = htons(port); ipAddress = inet_addr(host); if (ipAddress < 0) { hostInfo = gethostbyname(host); ipAddress = *(long *)*hostInfo->h_addr_list; } sockInfo.sin_addr.s_addr = ipAddress; // 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"); return sock; }