Código
#include <stdlib.h> #include <string.h> #include <stdio.h> #include <unistd.h> #include <sys/socket.h> #include <arpa/inet.h> #include <netinet/in.h> #include <netdb.h> #include <sys/sendfile.h> //Sirve para poder enviar archivos #include <sys/types.h> //Sirve para poder recivir archivos #include <linux/if_packet.h> #include <sys/ioctl.h> // Estas 2 librerias son para poder saber algunos datos sobre el #include <net/if.h> // Cliente en cuention #define BUFFSIZE 1 #define ERROR -1 #define BUFFERSIZE 512 // Funciones // int login(int socket_cliente); void direccip(int socket_cliente, struct sockaddr_in addr); void salir(int socket_servidor, int socket_cliente); int intentos = 0; int main(){ int socket_servidor; //Socket del servidor para escuchar mensajes int socket_cliente; //Socket del cliente para enviar mesajes int puerto = 8081; //Numero de puerto en /etc/service char BUFFER[BUFFERSIZE]; //Mensaje para usar los comandos FILE * archivo; //Archivo sin formato socket_servidor = socket(AF_INET, SOCK_STREAM, 0); socklen_t longc; // Declaracion de las escructuras; struct sockaddr_in servidor, cliente; //Creamos las estructuras del cliente y servidor al mismo tiempo bzero((char *)&servidor, sizeof(servidor)); //Primero llenamos de 0's la struct servidor.sin_family = AF_INET; //Asiganamos la estructura servidor.sin_port = htons(puerto); //Indicamos el puerto servidor.sin_addr.s_addr = INADDR_ANY; //Esta macro especifica nuestra direccion if(bind(socket_servidor, (struct sockaddr *)&servidor, sizeof(servidor)) < 0){ //asignamos un puerto al socket return 1; } listen(socket_servidor,3); //Escuchamos por este puero maximo 2 clientes distintos intentos = 0; longc = sizeof(cliente); //Asignamos el tamano de la estructura a esta variable socket_cliente = accept(socket_servidor, (struct sockaddr *)&cliente, &longc); // Esperamos una conexion if(socket_cliente == -1){ return 1; } //Login con el servidor int conexion = login(socket_cliente); if(conexion == 12){ bzero(BUFFER, BUFFERSIZE); recv(socket_cliente,BUFFER,50,0); direccip(socket_cliente, cliente); } salir(socket_servidor, socket_cliente); } } } } } int login(int socket_cliente){ char user[8]; char pass[8]; if(intentos == 3){ close(socket_cliente); return 0; } send(socket_cliente,"Usuario: ",10,0); read(socket_cliente,user,9); send(socket_cliente, "Contrasena: ", 12, 0); read(socket_cliente, pass, 8); send(socket_cliente,"Bienvenido\n",12,0); }else{ send(socket_cliente,"ERROR\n",7,0); intentos = intentos + 1; login(socket_cliente); } }else{ send(socket_cliente,"ERROR\n",7,0); intentos = intentos + 1; login(socket_cliente); } } void direccip(int socket_cliente, struct sockaddr_in addr){ write(socket_cliente, "Tu eres: ",9); write(socket_cliente, inet_ntoa(addr.sin_addr), 16); write(socket_cliente,"\n",2); } void salir(int socket_servidor, int socket_cliente){ write(socket_cliente, "ADIOS ;)\n", 10); close(socket_cliente); }