#include #include #include #include #include int main() { int socket_id; int socket_acc; socklen_t s_lon; int r; struct sockaddr_in direccion; char hostName[255]; struct hostent *host; char texto[255]; printf("Servidor de sockets de mensajes de texto.\n"); socket_id = socket(AF_INET, SOCK_STREAM, 0); if (socket_id == -1) { perror("Error creando socket."); return -1; } gethostname(hostName, 255); host = gethostbyname(hostName); if (host == NULL) { perror("Error obteniendo información del host"); return -1; } direccion.sin_family = AF_INET; direccion.sin_port = htons(4242); memmove(&direccion.sin_addr, host->h_addr, host->h_length); r = bind(socket_id, &direccion, sizeof(direccion)); if ( r == -1) { perror("Error vinculando socket a dirección"); return -1; } //while (1) { printf("Esperando conexiones.\n"); r = listen(socket_id, 10); if (r == -1) { perror("Error esperando conexiones."); return -1; } // Aceptamos conexiones de manera infinita //while(1) { s_lon = sizeof(direccion); socket_acc = accept(socket_id, &direccion, &s_lon); if (socket_acc == -1) { perror("Error aceptando conexion."); return -1; } while(1) { r = recv(socket_acc, texto, 255, /*MSG_WAITALL*/0); // r = read(socket_acc, texto, 255); if (r == -1) perror("Error recibiendo mensaje."); else { printf("Mensaje recibido: \n"); write(1, texto, r); printf("\n"); } if (r == 0) break; //close(socket_acc); } //printf("Conexión recivida.\n"); close(socket_acc); close(socket_id); return 0; }