/******************************************************************************
*
* autor: Daniel Lerch Hostalot
* 04 Julio 2003
*
******************************************************************************/
#include <stdio.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
#include <signal.h>
#define BUFFER_SIZE 1024
/*
* Ejemplo Socket servidor TCP
*/
int main() {
/* Descriptor del socket */
int socket_descriptor;
/* Puerto al que escuchara el servidor */
int port = 9999;
/* Configuracion del socket */
struct sockaddr_in sin;
/* Crea un socket TCP */
socket_descriptor = socket (AF_INET, SOCK_STREAM, 0);
if (socket_descriptor == -1) {
perror("socket()");
exit(EXIT_FAILURE);
}
/* Configura el socket */
bzero (&sin, sizeof(sin));
sin.sin_family = AF_INET;
sin.sin_addr.s_addr = INADDR_ANY;
sin.sin_port = htons (port);
/* Une el socket al puerto X */
if (bind(socket_descriptor,(struct sockaddr *)&sin,sizeof(sin)) == -1) {
perror("bind()");
exit(EXIT_FAILURE);
}
/* Configura la cola del socket */
if (listen(socket_descriptor, 20) == -1) {
perror("listen()");
exit(EXIT_FAILURE);
}
/* Para obtener la configuracion del socket */
struct sockaddr_in pin;
int address_size;
/* Descriptor del socket temporal */
int temp_socket_descriptor;
/* Buffer de recepcion */
char buffer[BUFFER_SIZE];
/* Bucle principal de recepcion y envio de paquetes */
while (1) {
/* Limpieza del buffer */
memset (buffer, '\0', BUFFER_SIZE);
/* Aceptamos la conexion */
temp_socket_descriptor =
accept(socket_descriptor,(struct sockaddr*)&pin,&address_size);
if (temp_socket_descriptor == -1) {
perror("accept()");
exit(EXIT_FAILURE);
}
/* Recibimos datos */
if (recv(temp_socket_descriptor,buffer,sizeof(buffer),0)==-1) {
perror("recv()");
exit(EXIT_FAILURE);
}
printf ("Recibido: %s\n",buffer);
/* Enviamos datos */
if (send(temp_socket_descriptor, "Recibido\n", 9,0) == -1) {
perror("send()");
exit(EXIT_FAILURE);
}
/* Cierre del descriptor de archivo */
close(temp_socket_descriptor);
}
}
|