elhacker.net cabecera Bienvenido(a), Visitante. Por favor Ingresar o Registrarse
¿Perdiste tu email de activación?.

 

 


Tema destacado: Recuerda que debes registrarte en el foro para poder participar (preguntar y responder)


  Mostrar Mensajes
Páginas: 1 2 [3] 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 ... 23
21  Programación / Programación C/C++ / Re: Chat con listas en C en: 21 Junio 2016, 15:34 pm
Ahi esta el problema al momento que tratas de acceder a auxHosts no esta inicializado. Actualmente apunta a NULL.

Tienes que ver por que no se inicializo.

Saludos!

Ya lo he solucionado. Simplemente debía reservar memoria para cHosts, por un problema en la funcion AddClient. Bueno, ya está, gracias.
22  Programación / Programación C/C++ / Re: Chat con listas en C en: 20 Junio 2016, 15:00 pm
Trata de imprimir el valor (Direccion apuntada de) de auxHosts antes del error, solo para ver que si este inicializado.

Me imprime esto:
Código:
(nil)
Violación de segmento (`core' generado)

Citar
Donde inicializas max (minusculas) No veo donde este y la otra es < o <= en el for es que no veo donde este inicializado y ni sobre que cosa estes iterando.

Saludos.

¿Qué? xd
23  Programación / Programación C/C++ / Chat con listas en C en: 20 Junio 2016, 14:35 pm
Hola.

Estoy haciendo un chat con listas en C y tengo algunos problemas a la hora de insertar los datos y tal, me da violaciones de segmento cuando quiero acceder a los datos y tal.

La estructura es esta:
Código
  1. typedef struct _ConnectedHosts {
  2.  int socket;
  3.  char *Alias;
  4.  char *ipAddr;
  5.  struct _ConnectedHosts *Next;
  6. } ConnectedHosts, *PConnectedHosts;

Para inicializar una estructura o crearla, utilizo esta funcion:
Código
  1. PConnectedHosts CreateClient(int socket) {
  2.  int addrlen;
  3.  char *ipAddr = (char *)calloc(INET_ADDRSTRLEN, sizeof(char));
  4.  struct sockaddr_in ConnectedAddr;
  5.  struct _ConnectedHosts *cHosts = (PConnectedHosts)malloc(sizeof(ConnectedHosts));
  6.  
  7.  addrlen = sizeof(ConnectedAddr);
  8.  if(getpeername(socket, (struct sockaddr *)&ConnectedAddr, &addrlen) < 0) {
  9.    return NULL;
  10.  }
  11.  
  12.  inet_ntop(AF_INET, &ConnectedAddr.sin_addr, ipAddr, INET_ADDRSTRLEN);
  13.  
  14.  cHosts->socket = socket;
  15.  cHosts->ipAddr = ipAddr;
  16.  cHosts->Alias = (char *)calloc(ALIASLEN, sizeof(char));
  17.  cHosts->Next = NULL;
  18.  
  19.  return cHosts;
  20. }

Para añadir una estructura nueva a la lista uso esta otra:
Código
  1. void AddClient(PConnectedHosts RemoteAddr, PConnectedHosts MainAddr) {
  2.  PConnectedHosts aux = MainAddr;
  3.  
  4.  if(MainAddr == NULL) {
  5.    MainAddr = RemoteAddr;
  6.  }
  7.  else {
  8.    while(aux->Next != NULL) {
  9.      aux = aux->Next;
  10.    }
  11.  
  12.    aux->Next = RemoteAddr;
  13.  }
  14. }

Para eliminar alguna estructura de la lista uso esta:
Código
  1. int DeleteClient(PConnectedHosts DeleteAddr, PConnectedHosts MainAddr) {
  2.  if(MainAddr == NULL || DeleteAddr == NULL) {
  3.    return 1;
  4.  }
  5.  
  6.  PConnectedHosts bAux;
  7.  PConnectedHosts aux = MainAddr;
  8.  PConnectedHosts aAux;
  9.  
  10.  while(aux != DeleteAddr) {
  11.    bAux = aux;
  12.    aux = aux->Next;
  13.    aAux = aux->Next;
  14.  }
  15.  
  16.  close(aux->socket);
  17.  free(aux->Alias);
  18.  free(aux->ipAddr);
  19.  free(aux);
  20.  
  21.  bAux->Next = aAux;
  22.  return 0;
  23. }

Y luego utilizo esta funcion para saber qué cliente ha enviado los datos (ya que se trata de un chat):
Código
  1. PConnectedHosts whatsClient(int socket, PConnectedHosts MainAddr) {
  2.  PConnectedHosts aux = MainAddr;
  3.  
  4.  if(aux != NULL) {
  5.    while(aux->Next != NULL && aux->socket != socket) {
  6.      aux = aux->Next;
  7.    }
  8.  }
  9.  
  10.  return aux;
  11. }

Y aquí está el codigo del servidor:
Código
  1. #include "WDestChat.h"
  2.  
  3. int main() {
  4.  int i, aux, max, cSocket, lSocket;
  5.  char Buffer[1025];
  6.  struct sockaddr_in ServerAddr, ClientAddr;
  7.  PConnectedHosts auxHosts = NULL;
  8.  PConnectedHosts cHosts = NULL;
  9.  fd_set master, temp;
  10.  
  11.  lSocket = CreateListenSocket(PORT, MAX, &ServerAddr);
  12.  if(lSocket < 0) {
  13.    PrintError("Error creating socket");
  14.    return 1;
  15.  }
  16.  
  17.  max = lSocket + 1;
  18.  FD_SET(lSocket, &temp);
  19.  
  20.  while(1) {
  21.    master = temp;
  22.    if(select(max, &master, NULL, NULL, NULL) < 0) {
  23.      PrintError("Error receiving information");
  24.      return 1;
  25.    }
  26.  
  27.    for(i = 0; i <= max; i++) {
  28.      if(FD_ISSET(i, &master)) {
  29.        if(i == lSocket) {
  30.          cSocket = AcceptClient(lSocket, &ClientAddr);
  31.          if(cSocket < 0) {
  32.            PrintError("Error accepting client");
  33.          }
  34.          else {
  35.            if(max < cSocket) {
  36.              max = cSocket + 1;
  37.            }
  38.            /* Creating client list */
  39.            auxHosts = CreateClient(cSocket);
  40.            if(auxHosts == NULL) {
  41.              PrintError("Error creating client list");
  42.            }
  43.            /* receiving the alias */
  44.            recv(cSocket, auxHosts->Alias, 15, 0);
  45.            /* adding client to structure */
  46.            AddClient(auxHosts, cHosts);
  47.            /* adding client to socket array */
  48.            FD_SET(cSocket, &temp);
  49.  
  50.            printf("New client connected\n");
  51.          }
  52.        }
  53.        else {
  54.          aux = recv(i, Buffer, 1024, 0);
  55.          if(aux == 0) {
  56.            printf("%d socket was closed the connection\n", i);
  57.            FD_CLR(i, &temp);
  58.            auxHosts = whatsClient(i, cHosts);
  59.            DeleteClient(auxHosts, cHosts);
  60.          }
  61.          else if(aux > 0) {
  62.            printf("%s\n", Buffer);
  63.            for(aux = 0; aux < max; aux++) {
  64.              if(aux == i || aux == lSocket) {
  65.                continue;
  66.              }
  67.              else {
  68.                auxHosts = whatsClient(aux, cHosts);
  69.                send(aux, auxHosts->Alias, 15, 0);
  70.                send(aux, Buffer, 1024, 0);
  71.              }
  72.            }
  73.            memset(Buffer, '\0', sizeof(Buffer));
  74.          }
  75.        }
  76.      }
  77.    }
  78.  }
  79.  close(lSocket);
  80.  return 0;
  81. }

Segun GDB da error en la línea 69, es decir, al intentar acceder a la posicion de memoria que contiene el alias. Me gustaría saber qué estoy haciendo mal. Al parecer a la hora de acceder a los datos accedo a posiciones erróneas.
24  Programación / Programación C/C++ / Cifrado hash SHA1 en C en: 29 Mayo 2016, 17:32 pm
Hola.
Estoy intentando cifrar cadenas con el hash SHA1 pero me devuelve la cadena en binario, y la quiero en texto. Ejemplo:
Código
  1. #include <stdio.h>
  2. #include <openssl/sha.h>
  3.  
  4. int main() {
  5.  char *a = "hola";
  6.  size_t len = sizeof(a);
  7.  unsigned char hash[40];
  8.  
  9.  SHA1(a, len, hash);
  10.  printf("%s\n", hash);
  11.  
  12.  return 0;
  13. }

Y me devuelve esto:
Código:
�X�{�]�Μ(`x�;6�

Gracias de antemano
25  Programación / Programación C/C++ / Re: Problema al liberar memoria con free() en: 21 Mayo 2016, 14:04 pm
En cuanto al código, reorganicé para 2 cosas:
-1: poner los '\0'
-2: no anexar el espacio a las cadenas. Para eso el 'else'.

Por lo demás, estaría bien que primero calculases la cantidad de argumentos que tiene la cadena, y luego hicieras los malloc. Sinó, tendrás un montón de memoria perdida.
siii, eso ya lo tenía puesto en el codigo, es que este no lo he actualizado. A ver que te parece este:
Código
  1. char **GetCommand(int maxLength, int *numArgs, int *background) { /*Recibe un comando*/
  2.  int argc, secArgc;
  3.  char *stdBuffer = (char *)calloc(sizeof(char) * maxLength, sizeof(char) + 1);
  4.  char **stdCommand = (char **)calloc(sizeof(char *) * (maxLength / 2) + 1, sizeof(char));
  5.  
  6.  argc = secArgc = *background = 0;
  7.  stdCommand[argc] = (char *)calloc(sizeof(char) * (maxLength / 6), sizeof(char));
  8.  
  9.  printf("%s ", COMMAND_PROMPT);
  10.  fgets(stdBuffer, maxLength, stdin);
  11.  stdBuffer[strlen(stdBuffer) - 1] = '\0';
  12.  
  13.  if(!seastr("&", stdBuffer)) {
  14.    *background = 1;
  15.  }
  16.  
  17.  while(*stdBuffer) {
  18.    if(*stdBuffer == '\n') {
  19.      break;
  20.    }
  21.  
  22.    if(*stdBuffer == ' ') {
  23.      *stdBuffer++;
  24.      if(*stdBuffer != '&') {
  25.        stdBuffer[++secArgc] = '\0';
  26.        secArgc = 0;
  27.        stdCommand[++argc] = (char *)calloc(sizeof(char) * (maxLength / 4), sizeof(char));
  28.      }
  29.    }
  30.    else {
  31.      stdCommand[argc][secArgc++] = *stdBuffer++;
  32.    }
  33.  }
  34.  *numArgs = argc;
  35.  
  36.  stdCommand[++argc] = NULL;
  37.  stdBuffer = NULL;
  38.  free(stdBuffer);
  39.  
  40. return stdCommand;
  41. }

Pongo lo del & porque al ser una shell, el & indica que el proceso será ejecutado en background y tal. Y en cuanto a la funcion seastr() es una funcion propia que busca en una cadena y devuelve ciertos valores:
Código
  1. int seastr(const char *str1 /*word*/,
  2.            const char *str2 /*string*/) {
  3. /*Returns 0 if str1 is in str2*/
  4.  if(str1 == NULL||str2 == NULL) {
  5.    return 1;
  6.  }
  7.  
  8.  char *cp = (char *)str2;
  9.  char *sr, *fr;
  10.  
  11.  while(*cp) {
  12.    sr = cp;
  13.    fr = (char *)str1;
  14.    while(*sr && *fr && (*sr == *fr)) {
  15.      sr++, fr++;
  16.    }
  17.    if(!*fr) {
  18.      return 0;
  19.    }
  20.    cp++;
  21.  }
  22. return 1;
  23. }

Si ves algo que se podría mejorar de ahí, por favor, dimelo. Gracias.
26  Programación / Programación C/C++ / Re: Problema al liberar memoria con free() en: 21 Mayo 2016, 13:41 pm
Vale, ya me ha quedado claro, gracias por la ayuda, camarada.
27  Programación / Programación C/C++ / Re: Problema al liberar memoria con free() en: 21 Mayo 2016, 10:54 am
Veo que estas separando por cada espacio por que no usas strtok?

Porque prefiero usar funciones mías. Una cosa, es lo mismo si hago esto:
Código
  1. free(stdLine);
Que si hago esto:
Código
  1. for(i = 0; i < 10; i++) {
  2.  free(stdLine[i]);
  3. }
  4. free(stdLine);

Y otra cosa... ¿Como puedo saber si un puntero está apuntando a alguna direccion de memoria?
Porque por ejemplo puedo declararlo pero no inicializarlo, y despues al liberarlo me da una violacion de segmento.

Gracias.
28  Programación / Programación C/C++ / Problema al liberar memoria con free() en: 21 Mayo 2016, 04:19 am
Hola.
Estoy haciendo una shell y de momento va bien xd el problema surge cuando quiero liberar la variable que contiene los argumentos. Adjunto codigo:
Código
  1. char **GetCommand(int maxLength) { /*Recibe un comando*/
  2.  int argc, secArgc;
  3.  char *stdBuffer = (char *)malloc(sizeof(char) * maxLength);
  4.  char **stdCommand = (char **)malloc(sizeof(char *) * (maxLength / 2));
  5.  
  6.  argc = secArgc = 0;
  7.  stdCommand[argc] = (char *)malloc(sizeof(char) * (maxLength / 4));
  8.  
  9.  printf("%s ", COMMAND_PROMPT);
  10.  fgets(stdBuffer, maxLength, stdin);
  11.  stdBuffer[strlen(stdBuffer) - 1] = '\0';
  12.  
  13.  while(*stdBuffer) {
  14.    if(*stdBuffer == '\n') {
  15.      break;
  16.    }
  17.  
  18.    if(*stdBuffer == ' ') {
  19.      secArgc = 0;
  20.      stdCommand[++argc] = (char *)malloc(sizeof(char) * (maxLength / 4));
  21.    }
  22.  
  23.    stdCommand[argc][secArgc++] = *stdBuffer++;
  24.  }
  25.  stdBuffer = NULL;
  26.  free(stdBuffer);
  27.  
  28. return stdCommand;
  29. }

Con esta función se recibe un comando. Y este sería el main:
Código
  1. char **stdLine = NULL;
  2.  
  3.  while(stdLine = GetCommand(1024)) { /*Mientras se reciba un comando*/
  4.    printf("%s\n", stdLine[0]);
  5.  
  6.    switch(comExecute((const char **)stdLine)) {
  7.      case 0: break;
  8.      case 1: perror("Can\'t execute these command\n");
  9.      case EXIT_COMMAND: exit = 1;
  10.    }
  11.    if(exit) { /*Si ha escrito 'exit'*/
  12.      break;
  13.    }
  14.  
  15.    free(stdLine);
  16.  }

El problema surge con el free(stdLine); que a la hora de imprimirlo se ve que se llena de basura o algo así, porque cuando se ejecuta el printf del main me saca carácteres raros al final de cadena que impiden que sea bien leida. He pensado en poner stdLine = NULL; pero lo que quiero es liberar memoria. ¿Sería lo mismo poner free(stdLine) que stdLine = NULL? Yo creo que no, pero como no me dedico a la programación profesionalmente, sino más por afición, pues no tengo mucha idea.

Gracias de antemano.
29  Foros Generales / Noticias / Re: Anonymous desactiva el sitio web de una rama armada del Ku Klux Klan en: 1 Mayo 2016, 04:56 am
Es un DDOS cuanto puede durar?  Como muuuucho una semana
Ya es una semana en la que no se han difundido esas ideas.
30  Foros Generales / Noticias / Re: Anonymous desactiva el sitio web de una rama armada del Ku Klux Klan en: 26 Abril 2016, 20:03 pm
Ufff seguro eso acaba con ellos y disuelve sus ideales...

Al menos ayuda a que no se distribuyan
Páginas: 1 2 [3] 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 ... 23
WAP2 - Aviso Legal - Powered by SMF 1.1.21 | SMF © 2006-2008, Simple Machines