2011:04:mini-cliente-em-c

Mini Cliente em C

Este é um exemplo de código para um cliente mínimo, que envia um byte (letra C) para o servidor, e lê outro byte do servidor, pela internet.

As tarefas para se conseguir isso são realizadas na ordem:

  1. Configuring environment… done!
  2. Creating socket… done!
  3. Connecting… done!
  4. Writing “C”… done!
  5. Reading… “S” done!

Abaixo o código:

/*
Program: mincli.c
Author: Dr Beco
Date: 2001-04-03
Objective:
 show a minimum client program that can
 connect to a network, write a byte, read a byte, disconnect
*/
 
#include <stdio.h>
#include <unistd.h>
#include <netinet/in.h>
#include <netdb.h>
 
#define BUFFER 2
 
int main(void)
{
  printf("Configuring environment... ");
 
  char data[BUFFER];
  const char *host_server="localhost";
  struct sockaddr_in dir;
  struct hostent *host;
  int aux, id, p=3333; //port
 
  dir.sin_port = p;
  dir.sin_family = AF_INET;
  host = gethostbyname(host_server);
  if(host == NULL)
    return -1;
  dir.sin_addr.s_addr = ((struct in_addr *)(host->h_addr))->s_addr;
  printf("done!\n");
 
  printf("Creating socket... ");
  id = socket(AF_INET, SOCK_STREAM, 0);
  if(id == -1)
    return -1;
  printf("done!\n");
 
  printf("Connecting... ");
  if(connect(id, (struct sockaddr *)&dir, sizeof(dir)) == -1)
    return -1;
  printf("done!\n");
 
  printf("Writing \"C\"... ");
  aux = send(id, "C", 1, MSG_NOSIGNAL);
  if(aux < 0)
    return -1;
  printf("done!\n");
 
  printf("Reading... ");
  aux = read(id, data , 1);
  if(aux!=1)
    return -1;
  printf("\"%c\"", data[0]);
  printf(" done!\n");
  return 0;
}
You could leave a comment if you were logged in.
  • 2011/04/mini-cliente-em-c
  • Last modified: 2011/04/03 22:48