SOCKETS - Linux :: Shell UDP - Cliente


/******************************************************************************
* Módulo: Shell UDP - Cliente
******************************************************************************/

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <netdb.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <sys/socket.h>
#define MAX_SIZE 255
#define MAX_BUFF 2048


int main(int argc, char *argv[])
{
int sock; // Handler del socket
struct hostent *he; // Informacion de host
struct sockaddr_in h_addr,s_addr;
int addr_len;
int bytes; // Numero de bytes enviados
char msg[MAX_SIZE];
char resp[MAX_BUFF];

if (argc != 3)
{
fprintf(stderr, "usage: shell-udp-clnt address port\n");
exit (EXIT_FAILURE);
}

printf ("Shell UDP - Cliente\n\n");

/* Obtenemos los datos de la maquina */
if ((he = gethostbyname(argv[1]))==NULL) {
herror("No se ha podido localizar el host!");
exit (EXIT_FAILURE);
}
else
{
printf ("Intentando conectar a: %s\n",
inet_ntoa(*(struct in_addr *)he->h_addr));
}

/* Abrimos el socket */
if ((sock=socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP))==-1) {

perror( "No se ha podido crear el socket!\n");
exit (EXIT_FAILURE);
}

memset(&(h_addr.sin_zero), '\0', 8);
h_addr.sin_family = AF_INET;
h_addr.sin_port = htons(atoi(argv[2]));

/* Pasamos la IP de notacion de puntos y numeros a bytes */
if (inet_aton(argv[1], &h_addr.sin_addr)==-1) {

fprintf(stderr, "inet_aton() Dirección IP %s inválida!\n",argv[1]);
exit(1);
}

addr_len = sizeof(struct sockaddr);

while(1)
{
printf("shell-udp>");
fgets(msg,MAX_SIZE,stdin);

if ((bytes=sendto(sock, msg, strlen(msg), 0,
(struct sockaddr *)&h_addr, addr_len))==-1)
{
perror("No se ha podido enviar el mensaje!");
}

if (bytes=recvfrom(sock,resp,MAX_BUFF-1,0,
(struct sockaddr *)&s_addr,&addr_len))
{
resp[bytes]='\0';
printf("Response: %s\n",resp);
}

fflush(stdin);
}

close(sock);
return 0;
}

Posted on 3:14 p. m. by skarvin and filed under | 0 Comments »

0 comentarios: