Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- #include <string.h>
- #include <unistd.h>
- #include <sys/types.h>
- #include <sys/socket.h>
- #include <netinet/in.h>
- #include <netdb.h>
- #define BUFFER_SIZE 1024
- void on_error(char *s) { fprintf(stderr,"%s\n",s); fflush(stderr); exit(1); }
- int main(int argc, char **argv) {
- int client_fd, porta, n;
- struct sockaddr_in serveraddr;
- struct hostent *server;
- char *hostname;
- char buf[BUFFER_SIZE];
- /** Controllo linea di comando **/
- if (argc != 3) {on_error("Uso: tcp_client [hostname] [porta]\n"); }
- hostname = argv[1];
- porta = atoi(argv[2]);
- /* Crea il socket */
- client_fd = socket(AF_INET, SOCK_STREAM, 0);
- if (client_fd < 0)
- on_error("Non riesco a creare il socket");
- /* Trasformare il nome host nel numero IP */
- server = gethostbyname(hostname);
- if (server == NULL) { on_error("Errore DNS"); }
- /* Costruire l'indirizzo Internet del server */
- bzero((char *) &serveraddr, sizeof(serveraddr));
- serveraddr.sin_family = AF_INET; /** Famiglia internet **/
- bcopy((char *)server->h_addr,
- (char *)&serveraddr.sin_addr.s_addr, server->h_length);
- serveraddr.sin_port = htons(porta); /** Porta **/
- /* Crea una connessione con il server */
- if (connect(client_fd, (struct sockaddr *) &serveraddr, sizeof(serveraddr)) < 0)
- on_error("Non riesco a connettermi");
- /* Leggi un messaggio dall'utente */
- printf("Scrivi il messaggio: ");
- bzero(buf, BUFFER_SIZE);
- fgets(buf, BUFFER_SIZE, stdin);
- /* Invia il messaggio al server */
- n = write(client_fd, buf, strlen(buf));
- if (n < 0)
- on_error("Non riesco al scrivere sul socket");
- /* Stampa la risposta del server */
- bzero(buf, BUFFER_SIZE);
- n = read(client_fd, buf, BUFFER_SIZE);
- if (n < 0)
- on_error("Non riesco a leggere dal socket");
- printf("Risposta del server: %s", buf);
- close(client_fd);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement