/* simple client */ /* compile on sun with gcc -lnsl -lsocket filename.c This client is actually pretty useless because it doesn't observe any proper protocol implemented on a server. It just keeps trying to read chunks of up to 1023 bytes, zero-terminate it, prints it out, and echos it back to the server. It gets the server ip and port as commandline arguments (argv[1] and argv[2]). ******** PLEASE NOTE ********* I should clarify something I said about the read function in class. if you read(sfd,buffer,10) and no byte is available, it will block until there's at least one byte for it to read. However, if you read(sfd,buffer,10), and there is only 5 bytes available, it will read the 5 bytes and return 5. So to make sure you have read 10 bytes, you need to check the value returned by read and issue read again to get the remaining bytes. I might have said somthing different from this in class - my apologies. This actually gets more complicated, since there are "blocking sockets" and "non-blocking" sockets. More on this later. */ #include #include #include #include #include #include #include #include // first command-line arg is sever ip, second is server port int main(int argc, char *argv[]) { int socklen, sockfd, result, i; struct sockaddr_in iaddr; // structure about server socket; char buffer[1024]; // generic buffer sockfd = socket(AF_INET,SOCK_STREAM,0); // 1 iaddr.sin_family = AF_INET; iaddr.sin_addr.s_addr = inet_addr(argv[1]); // server ip iaddr.sin_port = htons(atoi(argv[2])); // server port result = connect(sockfd,(struct sockaddr *)&iaddr, sizeof(iaddr)); // result not -1 if sucessful if (result < 0) exit(1); /* you can also create streams: FILE *scin, *scout; scin = fdopen(sockfd,"r"); scout = fdopen(dup(sockfd),"w"); now you can use fprintf(scout,... and fscanf(scin,... DON'T forget to call fflush(scout); after writes. */ // read bytes and print as ascii: result = 1; while (result > 0) { result = read(sockfd,buffer,1023); buffer[result] = '\0'; // 0-terminate string (note not '0' but '\0') printf("%s\n",buffer); write(sockfd,buffer,result); // send stuff back } // while close(sockfd); exit(0); }