home
***
CD-ROM
|
disk
|
FTP
|
other
***
search
/
ftp.disi.unige.it
/
2015-02-11.ftp.disi.unige.it.tar
/
ftp.disi.unige.it
/
pub
/
.person
/
GianuzziV
/
SO1
/
echo_client.c
< prev
next >
Wrap
C/C++ Source or Header
|
2005-04-03
|
3KB
|
85 lines
/**********************************************************************************
* Programma: echo_client *
* *
* finalita': si collega con un server (echo_server) *
* Invia al server una stringa letta sullo standard input *
* e la riceve come eco *
* *
* Sintassi: echo_client [ host ] *
* host - nome dell'host su cui risiede il server *
* *
***********************************************************************************/
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#define SERVER 3123
char stringa[20]; /* stringa da fare echo */
main (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 */
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, (struct sockaddr *) &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);
}