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

 

 


Tema destacado: (TUTORIAL) Aprende a emular Sentinel Dongle By Yapis


  Mostrar Temas
Páginas: [1]
1  Programación / Programación C/C++ / Problema con linux sockets en c en: 14 Marzo 2015, 21:49 pm
Buenas, pedirles ayuda con un programita de sockets, el mensaje "Hello World" no se reproduce por pantalla.
Decir que son solo las funciones de la connexion de sockets, hay algunas funciones que no estas ^^

Gracias de antemano.

SERVIDOR

Código:
 */
int process_msg(int sock, struct _DNSTable *dnsTable)
{
  unsigned short op_code;
  char buffer[MAX_BUFF_SIZE];
  int done = 0;
  int size;

  //TODO: ....
  op_code = ldshort(buffer);
  switch(op_code)
  {
    case MSG_HELLO_RQ:
        printf("HELLO\n");
        bzero(buffer,sizeof(buffer)); // NECESARIO Poner el buffer a 0
        stshort(2,buffer);//fiquem el codigo del mensaje
        strcpy(buffer, "Hello World\0");//|02|Hello World|0|
        size=14;
        break;
      break; 
    case MSG_LIST_RQ:
      process_LIST_RQ_msg(sock, dnsTable);
      break;                 
    case MSG_FINISH:
      //TODO
      done = 1;
      break;
    default:
      perror("Message code does not exist.\n");
  }
    if(send(sock, buffer, size, 0) < 0)
    {
     perror("SEND FAIL");
     close(sock);
     exit(1);
    }
   
    return done;
}

int main (int argc, char *argv[])
{
  struct _DNSTable *dnsTable;
  int port;
  char dns_file[MAX_FILE_NAME_SIZE];
  char buffer[MAX_BUFF_SIZE];
  short opcode;
  getProgramOptions(argc, argv, dns_file, &port);
 
  dnsTable = loadDNSTableFromFile(dns_file);
  printDNSTable(dnsTable);

  int s;
  int sock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP); // crea el socket del servidor
 
 
  //LOCAL SERVER CODE
  struct sockaddr_in local, client;//struct del host local
  local.sin_family=AF_INET;
  local.sin_port= htons(DEFAULT_PORT); // cambiar por port
  local.sin_addr.s_addr=INADDR_ANY;
             
  //CALL BIND 
  if( bind(sock, (struct sockaddr *) &local, sizeof(local)) < 0)
  {
    perror("BIND FAIL");
  }
 
  //CALL LISTEN
  if( listen(sock, 5) == -1 )
  {
    perror("LISTEN FAIL");
  }

  while(1)
  {
    //Dentro del bucle infitino para que este el servidor siempre a la espera
    s = accept(sock, (struct sockaddr *) &client, sizeof(client));
    if(s == -1)
    {
      perror("ACCEPT FAIL");
    }else{
      process_msg(sock, &dnsTable);
    }
  }
 
 
  return 0;
}

CLIENTE

Código:
void holamundo(int sock)
{
// esto es lo que se le enviara al servidor
int Opcode = 1;
int sizeop = 2; // Tamaño del Opcode de envio de la comanda holamundo
char buffer[125]; //LA operacion holamundo segun la tabla de opcode recibira 14 bytes (1 char -> 1 byte)

printf("HELLORQ\n");
stshort(Opcode, buffer); //stshort(01, buffer); stshort(HELLORQ, buffer);
printf("%d\n", Opcode);
if(send(sock, buffer, sizeof(buffer), 0) < 0)
{
perror("SEND IN CLIENT FAIL");
}
recv(sock, buffer, sizeof(buffer), 0);
printf("%s\n", buffer);

}


/*
 * Function that process the menu option set by the user by calling
 * the function related to the menu option.
 * @param s The communications socket
 * @param option the menu option specified by the user.
 */
void process_menu_option(int s, int option)
{  
  switch(option){
    // Opció HELLO
    case MENU_OP_HELLO:
      holamundo(s);
      break;
    case MENU_OP_LIST:
      process_list_operation(s);
      break;
    case MENU_OP_FINISH:
      //TODO:
      break;
               
    default:
          printf("Invalid menu option\n");
  }
}


int main(int argc, char *argv[])
{
int port; // variable per al port inicialitzada al valor DEFAULT_PORT (veure common.h)
char host[MAX_HOST_SIZE]; // variable per copiar el nom del host des de l'optarg
int option = 0; // variable de control del menu d'opcions
int ctrl_options;
int sock;
char buffer[MAX_BUFF_SIZE];
int sizeop;
int Opcode;

int s = socket(AF_INET, SOCK_DGRAM,0); // He aqui el socket

//Control de error sobre los parametros recividos por referencia
  ctrl_options = getProgramOptions(argc, argv, host, &port);
  printf("que vale host aqui%s\n", host);
if(ctrl_options<0)
{
perror("No s'ha especificat el nom del servidor o el port\n\n");
close(s);
return -1;
}

struct sockaddr_in client;//struct in_client_from_server

client.sin_family=AF_INET;
client.sin_port=htonl(port);
client.sin_addr.s_addr=INADDR_ANY;

struct sockaddr_in server; //struct in_client_to_server

server.sin_family=AF_INET;
server.sin_port=htonl(DEFAULT_PORT);
setaddrbyname(&server,argv[2]);

bind()
//CLIENT MODE
  //TODO: setting up the socket for communication
if(connect(s, (struct sockaddr *) &server, sizeof(server)) < 0)// CONECTING SOCKET
{
perror("CONNECT FAIL");
close(s);
exit(1);
}
//send(s, "HOLA", sizeof("HOLA"), 0);


//MENU & START
  do{
      printa_menu();
// getting the user input.
scanf("%d",&option);
printf("\n\n");
process_menu_option(s, option);  // De forma original le enviava una variable s... si es el socket yo lo llamo sock

  }while(option != MENU_OP_FINISH); //end while(opcio)
 
  return 0;
}

Muestro tambien los resultados que me da el strace

SERVER

Código:
socket(PF_INET, SOCK_STREAM, IPPROTO_TCP) = 3
bind(3, {sa_family=AF_INET, sin_port=htons(2222), sin_addr=inet_addr("0.0.0.0")}, 16) = 0
listen(3, 5)                            = 0
accept(3,


CLIENT

Código:
socket(PF_INET, SOCK_STREAM, IPPROTO_TCP) = 3
bind(3, {sa_family=AF_INET, sin_port=htons(2222), sin_addr=inet_addr("0.0.0.0")}, 16) = 0
listen(3, 5)                            = 0
accept(3,

2  Programación / Programación C/C++ / Problemas pasando por referencia un char... en: 19 Diciembre 2014, 00:02 am
Código:
#include <stdlib.h>
#include <stdio.h>
#include <err.h>
#include <pthread.h>

#define NUM_THREADS 10


typedef struct
{
char* tcomanda;
int tcores;
int tmemory;
int tnumero;

}sthread;


void Inicializar(char file,sthread t[])
{

printf("%c\n", file);
//FILE *File = fopen(file, "r"); //Abrir archivo que se le pasa por referencia

int tata=sizeof(file);
printf("%d\n", tata);


char *line;
size_t len;
int i=-1;//Le damos valor -1 para que la primera linea de COMANDO sea en i=0
int numcomands;

char comanda; //Variables en las que se guardaran el resultado de leer el archivo
int coreses;
int rmdmen;

if(File == NULL)
{
err(1, "commands.txt");
}//File Error Control

while( i <= NUM_THREADS &&  getline(&line,&len,file) != -1)
{
if (i<0)
{
sscanf(line, "%d", &numcomands); //Tenemos en cuenta que la primera linea es el 10
++i;
}else{
sscanf(line, "%[^'·']·%02d·%d", comanda, &coreses, &rmdmen); //Sacamos de la linea obtenida la informacion
t[i].tcomanda=comanda;//Y la guardamos en la estructura
t[i].tcores=coreses;
t[i].tmemory=comanda;
++i;

printf("%s\n", );
}
}
}


// argv[0]~= ./Prac3 ||argv[1]~= commands.txt ||argv[2]~= nCores || argv[3]~= nMemoria
int main(int argc, char *argv[])
{
if(argc!=4){ //Un control de error para los argumentos pasados por la consola

printf("ERROR_ENTER:\n./file.c Filename nCores RAM\n");
return 0;
}

sthread t[NUM_THREADS]; //array de NUM_THREADS elementos de tipo structhreads
//pthread_attr_t attr;
//pthread_attr_init(&attr);
//pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE); //incluye la creación del proceso como DEPENDIENTE (JOINABLE)
int i;

int T_cores = atoi(argv[2]);
int T_memory = atoi(argv[3]);
char *file = argv[1];

printf("\n ##############-!MAIN!-##############");
printf("\n RECURSO_CORE:%d\n", T_cores);
printf("\n RECURSO_MEMORIA:%d\n", T_memory);
printf("\n ARCHIVO_COMANDOS:%s\n", T_file);
printf("\n ##############-!MAIN!-##############\n");
//CONDICION MUTEX DE ESPERA
Inicializar(file,t[NUM_THREADS]); // el nombre de un array es un puntero a la primera posición de memoria de un array
//CONDICION SIGNAL

int tata=sizeof(T_file);
printf("%d\n", tata);
return 0;
}//FREE TPB!!

Buenas People!!

Os comento, es el principio de un ejercicio de threads donde hayq ue pasarle el nombre de un archivo para lohabra lo lea sace unos comandos en bash que hay dentro y los ejecute....

El FILE se le pasa por el argv[1] el que lo pasamos a una variable char y lo enviamos a la funcion inicializa(...)

Pero no funciona, de hecho con el printf() en la funcion por consola salen caracteres raros (conclusion.. no lee el char)

¿QUE OPINAN?
Paz.
3  Programación / Programación C/C++ / Problemas con GetLIne y Threads en c en: 14 Diciembre 2014, 18:23 pm
Buenas, veran el siguiente codigo siempre de devuelve "Violacion del Segmento". Me imajino porque es... Ya que intento pasar directamente el resultado del getline() como parametro al thread, pero ya he intentado de todo xD

¿alguna idea?

Código:
#include <pthread.h>
#include <stdio.h>
#include <err.h>

#define NUM_THREADS 10

pthread_mutex_t mutex;
pthread_cond_t tickets_ready;

int tickets = 2;

void* pthread_function(void *myline)
{
char *theline;
pthread_mutex_lock(&mutex);
while(tickets==0)
{
pthread_cond_wait(&tickets_ready,&mutex);
}

-- tickets;
pthread_mutex_unlock(&mutex);

theline = (char *)myline;
printf("Thread working: ¡this is my line! -> %s\n", theline);
sleep(1);


pthread_mutex_lock(&mutex);
++tickets;
if (tickets>=1)
{
pthread_cond_broadcast(&tickets_ready);
/* code */
}

pthread_mutex_unlock(&mutex);
pthread_exit(NULL);
}

int main(int argc, char** argv)
{
pthread_t thread[NUM_THREADS];

long int i=0;
char *line;
//char *lines[NUM_THREADS];

FILE *file = fopen("commands.txt", "r");
char *data;
size_t len;


if(file == NULL)
{
err(1, "commands.txt");
}


while( i < NUM_THREADS &&  getline(&line,&len,file) != -1)
{
//fprintf(&lines[i], "%s\n", &line);
pthread_create(thread+i, NULL, pthread_function, (void *)line);
++i;
}

for ( i = 0; i < NUM_THREADS; ++i)
{
pthread_join(thread[i], NULL);
}
return 0;
}
4  Comunicaciones / Redes / Problemas con server ssh en: 28 Septiembre 2013, 06:27 am
Buenas, desde hace tiempo que quiero hacer un tunnel ssh porque la conexion desde le que me conecto esta con un proxy que limita vastante.

Pero mi problema no es con el tunnel en si. Si  no con el servidor shh que monte.

Pese a que a ete entro desde linux con Openssh. El server lo monte en una maquina windows con freessh

Para loguearme no me da ningun problema... incluso me entra a la cmd.exe del servidor.
Eso si una vez alli, no me permite meter ningun comando (mi idea era usarlo de forma remota en terminal en la red de trabajo)

¿Porque esto?¿Alguien tiene alguna solucion?

Gracias de antemano
Salu2
JoMoZa

(
Páginas: [1]
WAP2 - Aviso Legal - Powered by SMF 1.1.21 | SMF © 2006-2008, Simple Machines