Implementación comunicación Cliente Servidor UDP (C)

Esta vez con protocolo UDP. Correspondiente a la clase de guido del 08/09/09
ServidorUDP.c
#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <ctype.h> #include <string.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <signal.h> #define PORT 5000 typedef struct sockaddr *sad; void error (char *s) { exit ((perror(s),-1)); } int main () { int sock; struct sockaddr_in sin, sin1; char linea[1024]; socklen_t l; int cto; if ((sock=socket(PF_INET, SOCK_DGRAM, )) < ) error ("socket"); sin.sin_family=AF_INET; sin.sin_port=htons(PORT); sin.sin_addr.s_addr=INADDR_ANY; if (bind(sock, (sad) &sin, sizeof sin) < ) error ("bind"); /*recibimos */ l = sizeof (sin1); if ((cto=recvfrom(sock, linea, sizeof linea, , (sad) &sin1, &l)) < ) error("recvfrom"); linea[] = ; printf("%s \n", linea); linea[]++; if(sendto(sock, linea, cto, , (sad) &sin1, l) < ) error("sendto"); close(sock); return ; }
ClienteUDP.c
#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <ctype.h> #include <string.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <signal.h> #define PORT 5000 typedef struct sockaddr *sad; void error (char *s) { exit ((perror(s),-1)); } int main () { int sock; struct sockaddr_in sin; char linea[1024]; socklen_t l; int cto; if ((sock=socket(PF_INET, SOCK_DGRAM, )) < ) error ("socket"); sin.sin_family=AF_INET; sin.sin_port=htons(PORT); inet_aton("127.0.0.1", &sin.sin_addr); if (sendto(sock, "hola mundo", 10, , (sad) &sin, sizeof sin) < ) error("sendto"); /*recibimos */ /* no necesitamos saber desde donde es la conexion, va aser desde el servidor * Podria hacerse para validar que es realmente el servidor quien contesta. */ if ((cto=recvfrom(sock, linea, sizeof linea, , NULL, NULL)) < ) error("recvfrom"); linea[] = ; printf("%s \n", linea); close(sock); return ; }
Trackback URL for "Implementación comunicación Cliente Servidor UDP (C)"
http://www.odiolasllaves.com.ar/trackback/119
»
- Inicie sesión o regístrese para enviar comentarios
