/* echoclient.c
si collega con il server sulla macchina "host"
Funziona in coppia con echoserver.c
*/
#include
#include
#include
#include
#include
#define SERVER 3123
main (argc, argv)
int argc;
char **argv;
{ int sockfd; /* socket descr. */
int len; /* n.ro byte dati ricevuti */
struct sockaddr_in sa; /* indirizzo Internet */
struct hostent *hp; /* risultato host name lookup */
struct servent *sp; /* risultato service lookup */
char buf[BUFSIZ]; /* informazioni da whois */
char *myname; /* nome di questo eseguibile */
char *host; /* nome dell'host remoto */
char stringa[20]; /* stringa da fare echo */
myname=argv[0];
if (argc != 2) {
printf("Usage: %s host \n", myname);
exit(1);
}
host=argv[1];
if (( hp=gethostbyname(host) )==NULL) {
printf("%s: %s: no such host \n", myname, host);
exit(1);
}
/* costruisce la struttura che contiene l'indirizzo dell'host
da contattare, e il tipo di indirizzamento usato */
bcopy((char *) hp->h_addr, (char *) &sa.sin_addr, hp->h_length);
sa.sin_family=hp->h_addrtype;
/* inserisce il socket number dentro la struttura del socket */
sa.sin_port=htons((short int) SERVER);
/* richiede un descrittore di socket */
if (( sockfd=socket(hp->h_addrtype, SOCK_STREAM, 0))<0 ) {
printf("%s: errore apertura socket \n", myname);
exit(1);
}
/* mi connetto con il server remoto */
if (connect(sockfd, &sa, sizeof sa)<0) {
printf ("%s: connessione rifiutata \n", myname);
exit(1);
}
printf("%s: stringa da inviare > ", myname);
scanf("%s",stringa);
if (write(sockfd, stringa, strlen(stringa)) != strlen(stringa)) {
printf("%s: write error \n", myname);
exit(1);
}
/* ricevo la replica */
while ((len=read(sockfd, buf, BUFSIZ))>0)
write(0, buf, len);
close(sockfd);
exit(0);
}