05-09-2016, 04:15 PM
Objective:
show a minimum client program that can
connect to a netw/*
Program: mincli.c
Author: Dr Beco, 2011-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;
}ork, write a byte, read a byte, disconnect