

Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!


** client.c - a stream socket client demo */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <netinet/in.h> //#include <sys/types.h> #include<errno.h> #include <sys/socket.h>
#define PORT 13 // the port client will be connecting to #define MAX_LINE_SIZE 256 // max number of bytes we can get at once
int main(int argc, char *argv[]) { int sockfd; struct sockaddr_in servaddr; // connector’s address information int errorVal; char recvline[MAX_LINE_SIZE+1];
if( argc < 2 ) { fprintf(stderr, "\nUse: %s
if (argc != 2) { fprintf(stderr,"usage: client serverIP\n"); exit(1); }
if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) == -1) { perror("socket"); exit(1); } servaddr.sin_family = AF_INET; // host byte order servaddr.sin_port = htons(PORT); // short, network byte order servaddr.sin_addr.s_addr = inet_addr(argv[1]); memset(&(servaddr.sin_zero), 0, 8); // zero the rest of the struct
if (connect(sockfd, (struct sockaddr *)&servaddr, sizeof(struct sockaddr_in)) == -1) { perror("connect");
exit(1); }
int nTotal = 0; int nReceived = 1; char ch = 0; while(nReceived>0){ nReceived= recv(sockfd, &ch, 1, 0); printf("%c", ch); if(ch != EOF ) { nTotal++; } }
fprintf(stderr, "\nReceived: %d", nTotal );
return 0; }