Docsity

A Stream Socket Client Demo I-Network Programming-Lab Report, Exercises of Network Programming

Toggle sidebar
bg1
/*
** 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 <IP ADDRESS OF SERVER>", argv[0]);
exit(0);
}
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);
}
docsity.com
pf2

Partial preview of the text

Download A Stream Socket Client Demo I-Network Programming-Lab Report and more Exercises Network Programming in PDF only on Docsity!

** 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 ", argv[0]); exit(0); }

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); }

docsity.com

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; }

docsity.com