#include<stdio.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<netdb.h>
#define MAXLINE 4096
/*Prints a message when an error occurs and
exits*/
void error(char*);
int
main(int argc, char** argv) {
/*This struct is used for geting the name of the server and
converting it
to an IP address using gethostbyname*/
struct hostent *hp;
/*The socket trough which the server will commmunicate with
client*/
int
sockfd;
/*The amount of data received*/
int
n;
/*the date received from the server is stored in recvline*/
char recvline[MAXLINE+1];
/*the stucture for the address of the Server*/
struct sockaddr_in servaddr;
/*we have <Executable> <Host Name>*/
if(argc!=2)
error("usage: a.out <Host Name>\n");
/*
we will store the IP address in hp by converting the host Name*/
/*
if the host name that is given is not valid ==> (hp==Null exit from the
program*/
if((hp = gethostbyname(argv[1]))==NULL)
error("host name error");
/*Create the socket */
/*Verify if it is created ==> (sockfd>0) else print a message and
exit*/
if((sockfd = socket(AF_INET, SOCK_STREAM,0))<0)
error("unable to open a socket\n");
/*Allocate the space for the address struct*/
bzero(&servaddr, sizeof(servaddr));
/*Fill the struct*/
servaddr.sin_family = AF_INET;
servaddr.sin_port = htons(13);
/*Copy the IP
address from hp to the struct sockaddress*/
bcopy(hp->h_addr,&servaddr.sin_addr,hp->h_length);
/*Connecting the Host to the Server*/
/*verify if the connection is established ==> the value returned by
connect>0 else print message and exit*/
if
(connect(sockfd, (struct sockaddr *)&servaddr,sizeof(servaddr))<0)
error("connect error\n");
/*Read the recvline*/
while ((n=read(sockfd,recvline,MAXLINE))>0) {
recvline[n] = 0;
/*print recvline */
if (fputs(recvline,stdout)==EOF)
error("fput error\n");
}
printf("\n");
if(n<0) error("read error");
}
void error (char* str){
printf("%s",str);
exit(1);
}