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

 

 


Tema destacado: Usando Git para manipular el directorio de trabajo, el índice y commits (segunda parte)


  Mostrar Temas
Páginas: [1] 2 3 4 5
1  Foros Generales / Foro Libre / Convertir PC en CCTV en: 8 Octubre 2016, 20:57 pm
Buenas! Como bien dice el título mi objetivo es convertir un PC en una CCTV pero me he dado cuenta de que la cosa no es tan sencilla como pensaba.
Mi idea es hacerme con una cámara de videovigilancia con salida coaxial para conectarla con un cable BNC a una capturadora de vídeo en el PC pero no se que capturadora de vídeo necesito. Seria posible conectar la señal de vídeo con un cable VGA a BNC a una tarjeta gráfica? O necesito una tarjeta especial para tal fin? Mi objetivo final es poder instalar un linux con zoneminder en el PC para hacer funcionar las cámaras. Si alguien puede orientarme se lo agradecería muchísimo!!

Gracias y un saludo de antemano!
2  Programación / Programación C/C++ / Ayuda con GetWindowText en: 20 Marzo 2013, 13:10 pm
Buenas, estoy intentando hacer un codigo en c++ para leer el texto de la ventana maximizada pero por algun motivo el texto no se lee apropiadamente...
Aquí les dejo el codigo:

Código
  1. #include "stdafx.h"
  2. #include <iostream>
  3. #include <Windows.h>
  4.  
  5. using namespace std;
  6.  
  7. int _tmain(int argc, _TCHAR* argv[]) {
  8. TCHAR title[500];
  9. ZeroMemory(title, sizeof(title));
  10. HWND wnd = GetForegroundWindow();
  11.  
  12. while (true) {
  13. HWND current = GetForegroundWindow();
  14. if (current!=wnd) {
  15. wnd = current;
  16. GetWindowText(wnd, title, 400);
  17. cout << "Text: " << title << endl;
  18. }
  19. Sleep(50);
  20. }
  21. return 0;
  22. }
  23.  
  24.  

Estoy haciendo pruebas con el Visual Studio 2012 pero al ejecutar el programa este siempre me devuelve un valor sin sentido EJ: 01AB8D9 lo cual supongo que debe ser basura... Si alguien puede explicarme que estoy haciendo mal estaria muy agradecido!!
3  Programación / Java / Duda sobre Imagenes en: 16 Febrero 2013, 00:30 am
Buenas, últimamente he estado investigando sobre imágenes en Java y lo que es realmente una imagen para poder desarrollar una aplicación que compare 2 imágenes y obtenga en forma de cadena de enteros la información dentro de la imagen, al hacer esto me han surgido unas cuantas dudas que me gustaría que me aclararan o bien donde puedo encontrar información al respecto. Bien empiezo:

Realizo una captura del escritorio de mi PC a una resolución de 1366x768 de tal modo que llamo a la clase robot y obtengo dicha captura en forma de BufferedImage, esta imagen no es más que una matriz 2D de pixels donde cada pixel según el tipo de imagen puede tener distinta información (almenos en java), suponiendo un tipo de imagen RGB cada pixel estaría compuesto de 3 datos que equivaldrían a 1 Byte cada uno que contendrían la información sobre el color (numero entero del 0-255), bien pues si sacamos cálculos teniendo en cuenta que tenemos una imagen de 1366x768 tenemos un total de 1,049,088 pixels donde cada pixel ocupa 3 Bytes es decir dicha imagen debería ocupar en realidad un total de 3,147,264 Bytes, esto es poco mas de 3MB ?? Como es esto posible si yo al almacenar dicha imagen mediante la clase ImageIO obtengo resultados entorno a 250 KB ? Además, las imágenes de esta resolución no pesan eso...

Donde está el truco?? Estoy seguro de que esto se debe a algún tipo de compresión de imágenes o algo por el estilo pues creo que mis cálculos son correctos...
4  Programación / Java / Registro Windows desde Java (WinRegistry) en: 4 Febrero 2013, 03:39 am
Buenas! Pues verán, buscando por internet un método adecuado para acceder al registro de Windows mediante Java encontré un código muy interesante pero que tiene la pega de ser detectado como una amenaza para por el mismísimo Windows Defender lo cual hace que la implementación de dicho codigo en cualquier aplicación no sea posible... Mi pregunta es: ¿Existe alguna manera de modificar el código para que sea posible evadir los mecanismos de detección? O dicho de otra forma, que parte del código es la que es detectada como una amenaza para Windows?

Código
  1. import java.lang.reflect.InvocationTargetException;
  2. import java.lang.reflect.Method;
  3. import java.util.ArrayList;
  4. import java.util.HashMap;
  5. import java.util.List;
  6. import java.util.Map;
  7. import java.util.prefs.Preferences;
  8.  
  9. public class WinRegistry {
  10.  public static final int HKEY_CURRENT_USER = 0x80000001;
  11.  public static final int HKEY_LOCAL_MACHINE = 0x80000002;
  12.  public static final int REG_SUCCESS = 0;
  13.  public static final int REG_NOTFOUND = 2;
  14.  public static final int REG_ACCESSDENIED = 5;
  15.  
  16.  private static final int KEY_ALL_ACCESS = 0xf003f;
  17.  private static final int KEY_READ = 0x20019;
  18.  private static Preferences userRoot = Preferences.userRoot();
  19.  private static Preferences systemRoot = Preferences.systemRoot();
  20.  private static Class<? extends Preferences> userClass = userRoot.getClass();
  21.  private static Method regOpenKey = null;
  22.  private static Method regCloseKey = null;
  23.  private static Method regQueryValueEx = null;
  24.  private static Method regEnumValue = null;
  25.  private static Method regQueryInfoKey = null;
  26.  private static Method regEnumKeyEx = null;
  27.  private static Method regCreateKeyEx = null;
  28.  private static Method regSetValueEx = null;
  29.  private static Method regDeleteKey = null;
  30.  private static Method regDeleteValue = null;
  31.  
  32.  static {
  33.    try {
  34.      regOpenKey = userClass.getDeclaredMethod("WindowsRegOpenKey",
  35.          new Class[] { int.class, byte[].class, int.class });
  36.      regOpenKey.setAccessible(true);
  37.      regCloseKey = userClass.getDeclaredMethod("WindowsRegCloseKey",
  38.          new Class[] { int.class });
  39.      regCloseKey.setAccessible(true);
  40.      regQueryValueEx = userClass.getDeclaredMethod("WindowsRegQueryValueEx",
  41.          new Class[] { int.class, byte[].class });
  42.      regQueryValueEx.setAccessible(true);
  43.      regEnumValue = userClass.getDeclaredMethod("WindowsRegEnumValue",
  44.          new Class[] { int.class, int.class, int.class });
  45.      regEnumValue.setAccessible(true);
  46.      regQueryInfoKey = userClass.getDeclaredMethod("WindowsRegQueryInfoKey1",
  47.          new Class[] { int.class });
  48.      regQueryInfoKey.setAccessible(true);
  49.      regEnumKeyEx = userClass.getDeclaredMethod(  
  50.          "WindowsRegEnumKeyEx", new Class[] { int.class, int.class,  
  51.              int.class });  
  52.      regEnumKeyEx.setAccessible(true);
  53.      regCreateKeyEx = userClass.getDeclaredMethod(  
  54.          "WindowsRegCreateKeyEx", new Class[] { int.class,  
  55.              byte[].class });  
  56.      regCreateKeyEx.setAccessible(true);  
  57.      regSetValueEx = userClass.getDeclaredMethod(  
  58.          "WindowsRegSetValueEx", new Class[] { int.class,  
  59.              byte[].class, byte[].class });  
  60.      regSetValueEx.setAccessible(true);
  61.      regDeleteValue = userClass.getDeclaredMethod(  
  62.          "WindowsRegDeleteValue", new Class[] { int.class,  
  63.              byte[].class });  
  64.      regDeleteValue.setAccessible(true);
  65.      regDeleteKey = userClass.getDeclaredMethod(  
  66.          "WindowsRegDeleteKey", new Class[] { int.class,  
  67.              byte[].class });  
  68.      regDeleteKey.setAccessible(true);
  69.    }
  70.    catch (Exception e) {
  71.      e.printStackTrace();
  72.    }
  73.  }
  74.  
  75.  private WinRegistry() {  }
  76.  
  77.  /**
  78.    * Read a value from key and value name
  79.    * @param hkey   HKEY_CURRENT_USER/HKEY_LOCAL_MACHINE
  80.    * @param key
  81.    * @param valueName
  82.    * @return the value
  83.    * @throws IllegalArgumentException
  84.    * @throws IllegalAccessException
  85.    * @throws InvocationTargetException
  86.    */
  87.  public static String readString(int hkey, String key, String valueName)
  88.  {
  89.    if (hkey == HKEY_LOCAL_MACHINE) {
  90.      return readString(systemRoot, hkey, key, valueName);
  91.    }
  92.    else if (hkey == HKEY_CURRENT_USER) {
  93.      return readString(userRoot, hkey, key, valueName);
  94.    }
  95.    else {
  96.      throw new IllegalArgumentException("hkey=" + hkey);
  97.    }
  98.  }
  99.  
  100.  /**
  101.    * Read value(s) and value name(s) form given key
  102.    * @param hkey  HKEY_CURRENT_USER/HKEY_LOCAL_MACHINE
  103.    * @param key
  104.    * @return the value name(s) plus the value(s)
  105.    * @throws IllegalArgumentException
  106.    * @throws IllegalAccessException
  107.    * @throws InvocationTargetException
  108.    */
  109.  public static Map<String, String> readStringValues(int hkey, String key)
  110.  {
  111.    if (hkey == HKEY_LOCAL_MACHINE) {
  112.      return readStringValues(systemRoot, hkey, key);
  113.    }
  114.    else if (hkey == HKEY_CURRENT_USER) {
  115.      return readStringValues(userRoot, hkey, key);
  116.    }
  117.    else {
  118.      throw new IllegalArgumentException("hkey=" + hkey);
  119.    }
  120.  }
  121.  
  122.  /**
  123.    * Read the value name(s) from a given key
  124.    * @param hkey  HKEY_CURRENT_USER/HKEY_LOCAL_MACHINE
  125.    * @param key
  126.    * @return the value name(s)
  127.    * @throws IllegalArgumentException
  128.    * @throws IllegalAccessException
  129.    * @throws InvocationTargetException
  130.    */
  131.  public static List<String> readStringSubKeys(int hkey, String key)
  132.  {
  133.    if (hkey == HKEY_LOCAL_MACHINE) {
  134.      return readStringSubKeys(systemRoot, hkey, key);
  135.    }
  136.    else if (hkey == HKEY_CURRENT_USER) {
  137.      return readStringSubKeys(userRoot, hkey, key);
  138.    }
  139.    else {
  140.      throw new IllegalArgumentException("hkey=" + hkey);
  141.    }
  142.  }
  143.  
  144.  /**
  145.    * Create a key
  146.    * @param hkey  HKEY_CURRENT_USER/HKEY_LOCAL_MACHINE
  147.    * @param key
  148.    * @throws IllegalArgumentException
  149.    * @throws IllegalAccessException
  150.    * @throws InvocationTargetException
  151.    */
  152.  public static void createKey(int hkey, String key)
  153.  {
  154.    int [] ret;
  155.    if (hkey == HKEY_LOCAL_MACHINE) {
  156.      ret = createKey(systemRoot, hkey, key);
  157.      regCloseKey.invoke(systemRoot, new Object[] { new Integer(ret[0]) });
  158.    }
  159.    else if (hkey == HKEY_CURRENT_USER) {
  160.      ret = createKey(userRoot, hkey, key);
  161.      regCloseKey.invoke(userRoot, new Object[] { new Integer(ret[0]) });
  162.    }
  163.    else {
  164.      throw new IllegalArgumentException("hkey=" + hkey);
  165.    }
  166.    if (ret[1] != REG_SUCCESS) {
  167.      throw new IllegalArgumentException("rc=" + ret[1] + "  key=" + key);
  168.    }
  169.  }
  170.  
  171.  /**
  172.    * Write a value in a given key/value name
  173.    * @param hkey
  174.    * @param key
  175.    * @param valueName
  176.    * @param value
  177.    * @throws IllegalArgumentException
  178.    * @throws IllegalAccessException
  179.    * @throws InvocationTargetException
  180.    */
  181.  public static void writeStringValue
  182.    (int hkey, String key, String valueName, String value)
  183.  {
  184.    if (hkey == HKEY_LOCAL_MACHINE) {
  185.      writeStringValue(systemRoot, hkey, key, valueName, value);
  186.    }
  187.    else if (hkey == HKEY_CURRENT_USER) {
  188.      writeStringValue(userRoot, hkey, key, valueName, value);
  189.    }
  190.    else {
  191.      throw new IllegalArgumentException("hkey=" + hkey);
  192.    }
  193.  }
  194.  
  195.  /**
  196.    * Delete a given key
  197.    * @param hkey
  198.    * @param key
  199.    * @throws IllegalArgumentException
  200.    * @throws IllegalAccessException
  201.    * @throws InvocationTargetException
  202.    */
  203.  public static void deleteKey(int hkey, String key)
  204.  {
  205.    int rc = -1;
  206.    if (hkey == HKEY_LOCAL_MACHINE) {
  207.      rc = deleteKey(systemRoot, hkey, key);
  208.    }
  209.    else if (hkey == HKEY_CURRENT_USER) {
  210.      rc = deleteKey(userRoot, hkey, key);
  211.    }
  212.    if (rc != REG_SUCCESS) {
  213.      throw new IllegalArgumentException("rc=" + rc + "  key=" + key);
  214.    }
  215.  }
  216.  
  217.  /**
  218.    * delete a value from a given key/value name
  219.    * @param hkey
  220.    * @param key
  221.    * @param value
  222.    * @throws IllegalArgumentException
  223.    * @throws IllegalAccessException
  224.    * @throws InvocationTargetException
  225.    */
  226.  public static void deleteValue(int hkey, String key, String value)
  227.  {
  228.    int rc = -1;
  229.    if (hkey == HKEY_LOCAL_MACHINE) {
  230.      rc = deleteValue(systemRoot, hkey, key, value);
  231.    }
  232.    else if (hkey == HKEY_CURRENT_USER) {
  233.      rc = deleteValue(userRoot, hkey, key, value);
  234.    }
  235.    if (rc != REG_SUCCESS) {
  236.      throw new IllegalArgumentException("rc=" + rc + "  key=" + key + "  value=" + value);
  237.    }
  238.  }
  239.  
  240.  // =====================
  241.  
  242.  private static int deleteValue
  243.    (Preferences root, int hkey, String key, String value)
  244.  {
  245.    int[] handles = (int[]) regOpenKey.invoke(root, new Object[] {
  246.        new Integer(hkey), toCstr(key), new Integer(KEY_ALL_ACCESS) });
  247.    if (handles[1] != REG_SUCCESS) {
  248.      return handles[1];  // can be REG_NOTFOUND, REG_ACCESSDENIED
  249.    }
  250.    int rc =((Integer) regDeleteValue.invoke(root,  
  251.        new Object[] {
  252.          new Integer(handles[0]), toCstr(value)
  253.          })).intValue();
  254.    regCloseKey.invoke(root, new Object[] { new Integer(handles[0]) });
  255.    return rc;
  256.  }
  257.  
  258.  private static int deleteKey(Preferences root, int hkey, String key)
  259.  {
  260.    int rc =((Integer) regDeleteKey.invoke(root,  
  261.        new Object[] { new Integer(hkey), toCstr(key) })).intValue();
  262.    return rc;  // can REG_NOTFOUND, REG_ACCESSDENIED, REG_SUCCESS
  263.  }
  264.  
  265.  private static String readString(Preferences root, int hkey, String key, String value)
  266.  {
  267.    int[] handles = (int[]) regOpenKey.invoke(root, new Object[] {
  268.        new Integer(hkey), toCstr(key), new Integer(KEY_READ) });
  269.    if (handles[1] != REG_SUCCESS) {
  270.      return null;
  271.    }
  272.    byte[] valb = (byte[]) regQueryValueEx.invoke(root, new Object[] {
  273.        new Integer(handles[0]), toCstr(value) });
  274.    regCloseKey.invoke(root, new Object[] { new Integer(handles[0]) });
  275.    return (valb != null ? new String(valb).trim() : null);
  276.  }
  277.  
  278.  private static Map<String,String> readStringValues
  279.    (Preferences root, int hkey, String key)
  280.  {
  281.    HashMap<String, String> results = new HashMap<String,String>();
  282.    int[] handles = (int[]) regOpenKey.invoke(root, new Object[] {
  283.        new Integer(hkey), toCstr(key), new Integer(KEY_READ) });
  284.    if (handles[1] != REG_SUCCESS) {
  285.      return null;
  286.    }
  287.    int[] info = (int[]) regQueryInfoKey.invoke(root,
  288.        new Object[] { new Integer(handles[0]) });
  289.  
  290.    int count = info[0]; // count  
  291.    int maxlen = info[3]; // value length max
  292.    for(int index=0; index<count; index++)  {
  293.      byte[] name = (byte[]) regEnumValue.invoke(root, new Object[] {
  294.          new Integer
  295.            (handles[0]), new Integer(index), new Integer(maxlen + 1)});
  296.      String value = readString(hkey, key, new String(name));
  297.      results.put(new String(name).trim(), value);
  298.    }
  299.    regCloseKey.invoke(root, new Object[] { new Integer(handles[0]) });
  300.    return results;
  301.  }
  302.  
  303.  private static List<String> readStringSubKeys
  304.    (Preferences root, int hkey, String key)
  305.  {
  306.    List<String> results = new ArrayList<String>();
  307.    int[] handles = (int[]) regOpenKey.invoke(root, new Object[] {
  308.        new Integer(hkey), toCstr(key), new Integer(KEY_READ)
  309.        });
  310.    if (handles[1] != REG_SUCCESS) {
  311.      return null;
  312.    }
  313.    int[] info = (int[]) regQueryInfoKey.invoke(root,
  314.        new Object[] { new Integer(handles[0]) });
  315.  
  316.    int count  = info[0]; // Fix: info[2] was being used here with wrong results. Suggested by davenpcj, confirmed by Petrucio
  317.    int maxlen = info[3]; // value length max
  318.    for(int index=0; index<count; index++)  {
  319.      byte[] name = (byte[]) regEnumKeyEx.invoke(root, new Object[] {
  320.          new Integer
  321.            (handles[0]), new Integer(index), new Integer(maxlen + 1)
  322.          });
  323.      results.add(new String(name).trim());
  324.    }
  325.    regCloseKey.invoke(root, new Object[] { new Integer(handles[0]) });
  326.    return results;
  327.  }
  328.  
  329.  private static int [] createKey(Preferences root, int hkey, String key)
  330.  {
  331.    return  (int[]) regCreateKeyEx.invoke(root,
  332.        new Object[] { new Integer(hkey), toCstr(key) });
  333.  }
  334.  
  335.  private static void writeStringValue
  336.    (Preferences root, int hkey, String key, String valueName, String value)
  337.  {
  338.    int[] handles = (int[]) regOpenKey.invoke(root, new Object[] {
  339.        new Integer(hkey), toCstr(key), new Integer(KEY_ALL_ACCESS) });
  340.  
  341.    regSetValueEx.invoke(root,  
  342.        new Object[] {
  343.          new Integer(handles[0]), toCstr(valueName), toCstr(value)
  344.          });
  345.    regCloseKey.invoke(root, new Object[] { new Integer(handles[0]) });
  346.  }
  347.  
  348.  // utility
  349.  private static byte[] toCstr(String str) {
  350.    byte[] result = new byte[str.length() + 1];
  351.  
  352.    for (int i = 0; i < str.length(); i++) {
  353.      result[i] = (byte) str.charAt(i);
  354.    }
  355.    result[str.length()] = 0;
  356.    return result;
  357.  }
  358. }
5  Programación / Programación C/C++ / Problema Función "OpenProcess" en: 2 Febrero 2013, 19:06 pm
Al llamar a la función OpenProcess(PROCESS_ALL_ACCESS, 0, pid) esta me devuelve NULL es decir no es capaz de abrir el proceso. Utilizando la función getLastError() esta me devuelve 5, es decir, problemas Administrativos por lo que tengo entendido (Lectura, Escritura). La cosa esta en como puedo solucionar esto para que si me sea posible obenter el proceso??

Nota: Estoy utilizando Microsoft Visual Studio C++ y Windows 8.

Para que se hagan una mejor idea aqui les dejo mi codigo:

Código
  1. #include "stdafx.h"
  2. #include <iostream>
  3. #include <Windows.h>
  4.  
  5. using namespace std;
  6.  
  7. int _tmain(int argc, _TCHAR* argv[])
  8. {
  9.  
  10. HWND hwnd = FindWindow(0, _T("NOMBRE_VENTANA"));
  11.  
  12. HANDLE hProcess;
  13.  
  14. DWORD pid;
  15.  
  16. if (!hwnd) {
  17. cout << "ERROR 1\n\n";
  18. } else {
  19. GetWindowThreadProcessId(hwnd, &pid);
  20.  
  21. cout << "PID = " << pid << "\n\n";
  22.  
  23. hProcess = OpenProcess(PROCESS_ALL_ACCESS, 0, pid); //PROBLEMA AQUI!!!
  24.  
  25. if (!hProcess) {
  26.                        cout << "ERROR = " << GetLastError() << "\n\n"; //OBTENEMOS ERROR = 5 (PRIVILEGIOS)
  27. } else {
  28. cout << "PROCESS OPENED\n\n";
  29.  
  30.                        //GESTIONAR...
  31. }
  32.  
  33. CloseHandle(hProcess);
  34.  
  35. }
  36.  
  37. cin.get();
  38. return 0;
  39. }
  40.  

A ver si alguien puede echarme una mano pues no se como salir adelante...
Saludos y gracias de antemano!!
6  Programación / Java / Can't load IA 32-bit en: 30 Enero 2013, 15:31 pm
Buenas! Veran, estaba siguiendo el tutorial del usuario Leyer para crear un Keylogger mediante JNI una vez tengo todo preparado y listo ejecuto el codigo y me manda el siguiente mensaje de Error:

Código:
Exception in thread "main" java.lang.UnsatisfiedLinkError: D:\RAT\Keylogger.dll: Can't load IA 32-bit .dll on a AMD 64-bit platform
at java.lang.ClassLoader$NativeLibrary.load(Native Method)
at java.lang.ClassLoader.loadLibrary1(ClassLoader.java:1939)
at java.lang.ClassLoader.loadLibrary0(ClassLoader.java:1864)
at java.lang.ClassLoader.loadLibrary(ClassLoader.java:1854)
at java.lang.Runtime.loadLibrary0(Runtime.java:845)
at java.lang.System.loadLibrary(System.java:1084)
at extras.Keylogger.<clinit>(Keylogger.java:8)
at extras.Main.main(Main.java:14)

La verdad no tengo ni idea de como solucionarlo y despues de haber googleado bastante sigo sin encontrar la solucion, el problema esta en intentar cargar la libreria y estoy usando la que Leyer ofrece en su ejemplo y una que yo mismo he compilado siguiendo sus instrucciones y obtengo el mismo problema...
7  Sistemas Operativos / Windows / Que es un .EXE exactamente?? en: 29 Diciembre 2012, 19:21 pm
Pues eso, he hecho alguna aplicacion en C y VB y he visto que se crean los tipicos ejecutables .EXE de windows. Por otro lado con la programacion en java he hecho alguna aplicacion y compilado en formato .JAR. Pues bien, resulta que un .JAR como muchos ya sabran no es mas que un .ZIP la pregunta es entonces, un .EXE tiene alguna relación con .ZIP o .RAR ?? He visto que es posible abrir un .EXE con WinRAR... quiere decir eso que puedo crear un .EXE indicando que incluya un archive que indique las acciones que debe realizar al ejecutar el archive y listo como si fuera un .JAR con un archivo MANIFEST.MF??

Corrijanme si me equivoco y en caso de estar en lo cierto, como se haria esto??
PD: FELIZ NAVIDAD!!
8  Programación / Java / Ayuda Java niv:Avanzado! en: 10 Diciembre 2012, 12:56 pm
Buenas, mi problema es el siguiente. Estoy intentando hacer un programa que en base a unos datos introducidos por el usuario la aplicacion los cogera para generar un archivo de salida con codigo en java que posteriormente sera compilado para crear un jar con las especificaciones que el usuario a introducido.
Estoy superconfundido y no se como hacerlo si alguien puede ayudar aunque sea dandome una idea para poder avanzar se lo agradeceria muchisiiimo!!
9  Programación / Java / [Source] Algoritmo Conjetura de Goldbach en: 10 Noviembre 2012, 22:05 pm
Pues bien, aqui les traigo un simple codigo que permite hallar todas las combinaciones posibles de 2 numeros primos que suman un numero par mayor que 2 (Conjetura de Goldbach).

Código
  1.  
  2. public class Goldbach {
  3.  
  4.    public static Boolean isPrime (int n) { //comprueba si 'n' es primo
  5.        int i=2;        
  6.        while (n%i!=0) i++;                    
  7.        if (i==n) return true;
  8.        else return false;
  9.    }
  10.  
  11.    public static void main(String[] args) {                
  12.        for (int i=2; i<50; i++) { // Buscamos combinaciones entre 2*2=4 y 50*2=100
  13.            for (int j=0; j+1<i; j++) { // Nota: j+1 para evitar el caso j=1 (1 no es primo)              
  14.                int p=i+j, q=i-j; // p & q primos a la misma distancia de 2*i por lo que su suma es 2*i
  15.                if ((isPrime(p)) && (isPrime(q)))            
  16.                    System.out.println("For number: "+2*i+" = "+p+" + "+q);                
  17.            }            
  18.            System.out.println("Number: "+2*i+" | Combos: "+nCombos);
  19.        }        
  20.    }
  21. }
  22.  

Ejemplo de salida :
Código:
For number: 4 = 2 + 2
For number: 6 = 3 + 3
For number: 8 = 5 + 3
For number: 10 = 5 + 5
For number: 10 = 7 + 3
For number: 12 = 7 + 5
For number: 14 = 7 + 7
For number: 14 = 11 + 3
For number: 16 = 11 + 5
For number: 16 = 13 + 3
For number: 18 = 11 + 7
For number: 18 = 13 + 5
For number: 20 = 13 + 7
For number: 20 = 17 + 3

A ver si con esto alguien se anima a demostrar la conjetura  :xD
Un saludo!
10  Programación / Java / Ayuda con Sockets en java en: 20 Agosto 2012, 04:48 am
Pues veran, estoy desarrolando una apliacion que se maneja con scokets para comunicarse con servidores y clientes utilizando los metodos DataOutputStream y DataInputStream. Bien, el caso es que estoy teniendo algunos problemillas pues no estoy muy familiarizado con los sockets, me gustaria saber que pasa y como debo reaccionar cuando un cliente no responde al servidor, poniendo el siguiente codigo de ejemplo:

Código
  1.    public class checkConnections extends Thread {        
  2.        public void run () {    
  3.            try {
  4.                DefaultTableModel t = (DefaultTableModel) jTable1.getModel();
  5.                User u = null;  
  6.                System.out.println("Checking connections...");
  7.                for (int i=0; i<users.size(); i++) {
  8.                    u = getUserAtRow(i);
  9.                    DataOutputStream dos = new DataOutputStream(u.getConnection().getOutputStream());
  10.                    dos.writeUTF("answer");
  11.                    String answer = dis.readUTF();
  12.                    if (!answer.equals("hi")) {
  13.                        users.remove(u);
  14.                        t.removeRow(i);
  15.                    }
  16.                }
  17.            }catch (IOException ex) { System.out.println("no answer"); }
  18.        }        
  19.    }

Para informarles, no esta de mas decir que los servidores conectados se encuentran en una tabla que gestiona el cliente, asi que va revisando que todos los servidores respondan.

Tal y como he dicho antes, este codigo pide a todos los servidores conectados que respondan mediante la instruccion answer. En el caso en que dicho servidor no este conectado por diversos motivos (fallo en la conexion, etc...), la llamada al metodo : dos.readUTF(); me devuelve un nullpointerexception que no se como gestionar, alguna idea?
Páginas: [1] 2 3 4 5
WAP2 - Aviso Legal - Powered by SMF 1.1.21 | SMF © 2006-2008, Simple Machines