Anuncio

martes, 29 de abril de 2014

Enrutamiento (NAT) en Linux

Se puede definir el enrutamiento como la capacidad de transmitir datos entre redes interconectadas. Al agente encargado de realizar este encaminamiento de información entre redes se conoce como enrutador o router pudiendo ser de tipo hardware si es un dispositivo físico dedicado al encaminamiento y de tipo software en caso de ser un PC que ejecuta una aplicación que realice las funciones propias del enrutamiento.
Con el software adecuado, nuestro servidor Linux podrá actuar de enrutador en nuestra red de manera que permitirá que los equipos de la red local se conecten a Internet como si lo hicieran a través de un router.

La tecnología empleada para permitir que los equipos de la red local se conecten a Internet a través de nuestro servidor Linux se denomina NAT - Network Address Traslation (Traducción de Direcciones de Red). El software NAT que se ejecuta en nuestro servidor permite, que con una única dirección IP pública en el servidor, tengan acceso a Internet el resto de PCs de la red.

En los PCs de la red local se deberá configurar como puerta de enlace (gateway) la dirección IP interna del servidor para que sea éste quien reciba y procese los paquetes provenientes de la red interna y con destino hacia Internet.

Cuando desde un PC de la red local se quiere acceder a Internet, el paquete de datos se enviará al servidor linux ya que es la puerta de enlace. El software NAT del servidor cambiará en el paquete de datos la dirección IP de origen del PC de la red local por la dirección IP pública del servidor y lanzará el paquete de datos hacia Internet. En una tabla interna almacenará el puerto de salida del paquete junto con la IP del PC de la red local con la finalidad de que cuando llegue la respuesta desde Internet, realizar el proceso inverso y poder redirigirlo hacia el PC que lanzó la petición.

Si nuestro servidor Linux, dispone además de servidor DHCP, la configuración de las direcciones IP, la puerta de enlace y el servidor DNS de nuestros PCs, podrá ser establecida automáticamente por el servidor DHCP.
Configuraciones establecidas automáticamente por el servidor DHCP
Una alternativa podría ser instalar en el servidor un proxy como squid, de esa forma las páginas accedidas por los clientes serían cacheadas en el servidor con lo cual se aceleraría la conexión a Internet, especialmente cuando son muchos los clientes que acceden a los mismos sitios. Un proxy facilita también el control de la conexión impidiéndola o restringiéndola a medida de nuestras necesidades. El inconveniente de compartir una conexión a Internet con un proxy es que trabaja a nivel de aplicación y por tanto del protocolo de cada aplicación (HTTP, FTP, SMTP, etc...). Esto obliga a configurar las aplicaciones (navegador, clientes de correo, clientes ftp, etc...) para que utilicen el proxy, cosa que no es necesario hacer cuando se dispone de un router ya que el router NAT trabaja a nivel de red TCP/IP y es totalmente trasparente a las aplicaciones.

Otro servicio que se podría disponer en el servidor es un cortafuegos como iptables que permite filtrar qué paquetes de datos pueden entrar y qué paquetes de datos pueden salir, con la finalidad de controlar el acceso a Internet y ganar en seguridad frente a ataques externos.

Más adelante veremos una configuración básica de iptables que nos permitirá permitir o denegar las conexiones a diferentes redes y puertos, así como una configuración básica de squid para poder compartir y controlar la conexión a Internet mediante el proxy.

Situación de partida

En nuestro Centro Educativo hemos venido detectando problemas de saturación de la línea de conexión a Internet sin motivo justificado. Hemos detectado que en algún ordenador de la sala de profesorado y de algún departamento hay instalados programas de P2P (descarga masiva) y somos conscientes de que estos programas saturan el canal de salida a Internet del centro, además sospechamos que el alumnado también utiliza este tipo de programas.

El router ADSL está conectado a un switch y por lo tanto a través de múltiples utilidades es fácil conocer su dirección IP y configurar nuestro equipo como puerta de enlace, con el consiguiente acceso libre a Internet y a la descarga masiva. Nos encontramos con un esquema del tipo:

Esquema en el que los PCs tienen acceso directo al router
Este esquema no permite controlar el tráfico de red puesto que los PCs tienen acceso directo al router.

Situando el servidor entre la red y el router, todo el tráfico hacia Internet pasa por el servidor lo que nos permitirá analizarlo, generar estadísticas, filtrar accesos, instalar un proxy-caché, etc., de forma sencilla y centralizada.

Situamos el servidor entre la red y el router

Activación del enrutamiento en Linux

Las funciones de enrutamiento mediante NAT son realizadas por el cortafuegos que analizará los paquetes provenientes de la red local interna cuyo destino sea Internet y los modificará convenientemente para que salgan hacia Internet como si fueran emitidos por el servidor. A partir del núcleo 2.4 de Linux, el cortafuegos empleado es iptables.

Para posibilitar que nuestro servidor Linux sea capaz de comportarse como un router y hacer de puerta de enlace para los PCs de nuestra red local, será necesario crear un script que configure el cortafuegos iptables para que realice NAT desde dentro de la red local hacia Internet.


Creación del script para activar enrutamiento

Para activar el enrutamiento en un sistema Linux, tan solo basta con poner a '1' la variable ip_forward del sistema, es decir, basta con ejecutar desde una consola de root:
// Activar el enrutamiento en un sistema Linux
sudo echo "1" > /proc/sys/net/ipv4/ip_forward
Posteriormente tendríamos que configurar el filtrado para que acepte el redireccionamiento de paquetes desde dentro hacia fuera de nuestra red y mediante NAT permita que los PCs de la red interna naveguen con la dirección IP 'publica' del servidor. Supongamos que el router Linux tiene una tarjeta (eth0) configurada con la IP 192.168.1.2/24 y conectada al router, cuya IP es 192.168.1.1/24, y por otro lado, tenemos otra tarjeta (eth1) configurada con la ip 10.0.0.1/8 y conectada al switch para dar servicio a nuestra red interna que utiliza el rango 10.0.0.0/8. Nuestro esquema sería como el que vemos en la siguiente figura:



Router Linux
Tendríamos que indicar que se acepten todos los paquetes que son para reenviar, es decir, aquellos que llegan a nuestra máquina pero que no es ella la destinataria. Para ello, tendríamos que aceptar los paquetes de tipo FORWARD, como veremos en la siguiente sección. Por otro lado, tendríamos que indicar que los paquetes que llegan desde nuestra red interna (-s 10.0.0.0/8) y que salgan por la interfaz eth0 hacia el router (-o eth0), después de enrutarlos en nuestra máquina (POSTROUTING), debemos enmascararlos (MASQUERADE), es decir, hacer NAT. Los comandos a ejecutar serían:
// Haciendo NAT en el servidor
sudo iptables -A FORWARD -j ACCEPT
sudo iptables -t nat -A POSTROUTING -s 10.0.0.0/8 -o eth0 -j MASQUERADE
Podríamos realizar un script que activara el enrutamiento y el NAT y otro para desactivarlo:
// activar-enrutamiento.sh
echo "1" > /proc/sys/net/ipv4/ip_forward
iptables -A FORWARD -j ACCEPT
iptables -t nat -A POSTROUTING -s 10.0.0.0/8 -o eth0 -j MASQUERADE

// desactivar-enrutamiento.sh
echo "0" > /proc/sys/net/ipv4/ip_forward
Así, nuestro servidor se convertiría en un router. Si todas las comunicaciones de la red pasan por nuestro servidor, podremos tenerlas controladas, como veremos en las siguientes secciones.

Crear y eliminar rutas fijas

Cuando activamos el enrutamiento en Linux, nuestra máquina se convierte en un router automático, de forma que todo lo que entre por la interfaz eth0 con destino a una red diferente de la definida en eth0, lo reenviará por la interfaz eth1 y de igual forma, todo lo que entre por la interfaz eth1 con destino a una red diferente de la definida en eth1, lo reenviará por la interfaz eth0. Es el funcionamiento normal de un router, enrutar todo.

En algunos casos, puede que nos interese que ciertos paquetes salgan por una interfaz concreta. Por ejemplo, supongamos que en nuestra red disponemos de dos conexiones ADSL independientes, una para dar servicio de conexión a Internet al servidor (interfaz de producción) y otra, para conectarnos desde nuestra casa al servidor, para realizar tareas de administración (interfaz de administración).Supongamos que la interfaz eth0 está conectada al router ADSL de producción y la interfaz eth1 está conectada al router ADSL para realizar tareas de administración.



Rutas fijas
Lo normal es que la interfaz eth0 tenga configurada como puerta de enlace la IP del router de conexión a Internet, pero la interfaz eth1 no debería tener configurada la puerta de enlace, para que no exista tráfico hacia Internet por dicha interfaz. Si en el ADSL de nuestra casa tenemos IP fija, podemos crear una ruta para que cuando la IP destino sea la IP fija de nuestra casa, los paquetes se enruten por eth1 en lugar de hacerlo por eth0. Ejemplo, si nuestra IP de casa es 80.58.12.27, el comando a ejecutar será:
//Crear una ruta para una IP concreta
sudo route add 80.58.12.27 eth1
En lugar de una IP concreta, quizás nos interese crear una ruta para toda una red. Supongamos que queremos que cuando la IP destino sea una IP del CNICE, salga por la interfaz eth1. Teniendo en cuenta que el rango de IPs públicas del CNICE es 192.144.238.0/24, el comando a ejecutar sería:
//Crear una ruta para una red concreta
sudo route add -net 193.144.238.0/24 eth1
Si queremos eliminar una ruta, utilizaremos el parámetro 'del' seguido de la IP o la red destinataria. Ejecutaríamos el siguiente comando:
//Eliminar una ruta
sudo route del -net 193.144.238.0/24
Si queremos ver la configuración de la tabla de rutas, debemos ejecutar el comando route sin parámetros:
//Ver rutas
sudo route
Establecer rutas puede ser muy interesante cuando queremos dividir nuestra red en diferentes subredes y disponemos de un servidor con varias tarjetas de red.

martes, 22 de abril de 2014

Creando estructura de un proyecto LibGdx


Fuente: http://desarrollodejuegosenandroid.blogspot.com.es/2013/07/3-creando-la-estructura.html


https://github.com/libgdx/libgdx/wiki/Quick-start


http://stackoverflow.com/questions/2590850/threading-in-gwt-client

http://www.pixnbgames.com/blog/libgdx/como-gestionar-varias-pantallas-en-libgdx/

https://github.com/libgdx/libgdx/wiki/Scene2d.ui#changeevents

http://libdgxtutorials.blogspot.com.es/2013/09/libgdx-tutorial-8-using-texture-packer.html

http://stackoverflow.com/questions/27714970/adding-a-clicklistener-to-a-textbutton-libgdx

http://libdgxtutorials.blogspot.com.es/2013/09/libgdx-tutorial-10-button-and-stage-2d.html

https://github.com/libgdx/libgdx/wiki/Texture-packer

http://stackoverflow.com/questions/21488311/how-to-create-a-button-in-libgdx

https://libgdx.badlogicgames.com/nightlies/docs/api/com/badlogic/gdx/scenes/scene2d/ui/Button.html

https://github.com/libgdx/libgdx/wiki/Continuous-&-non-continuous-rendering


How to Fix : Android SDK Manager failing to open in Android Development Tools Bundle



Fuente: http://techathlon.com/fix-android-sdk-manager-failing-open-android-development-tools-bundle/

Restaura imagen del sistema en otro disco duro / Restoring system image to a different harddrive



Fuente: http://www.softzone.es/2009/07/27/driveimage-xml-crea-imagenes-de-tu-disco-duro-con-este-programa-gratuito-mini-tutorial-de-driveimage-xml/

Web Oficial: http://www.runtime.org/driveimage-xml.htm

LibGdx en español



Fuente: http://libgdxspain.blogspot.com.es/

domingo, 20 de abril de 2014

Emulador de Android "Snapshot" y "Use Host CPU"

The Snapshot option speeds up the boot of the emulator by saving a snapshot of its RAM once it has booted, and restoring from that snapshot on future uses. That way, it doesn't have to run the boot process (which is slow, because it's emulated) every time you start the emulator.
The Use Host GPU option uses the host computer's OpenGL implementation (which is probably hardware-accelerated, on your real GPU) to evaluate OpenGL commands inside the emulated system. Put another way, when a program inside the emulator uses OpenGL for graphics operations, the work goes out to your real GPU, and the result goes back into the emulator, instead of emulating a GPU (which is very slow). The result is a significant speed-up, especially when you consider that most view and canvas drawing uses OpenGL in Android ≥ 4, even in non-graphics apps.


Configurar proyecto Libgdx manualmente



Fuente: https://github.com/libgdx/libgdx/wiki/Manual-project-setup#android-project-setup

Configurar correctamente ADT PLUGIN Android SDK



Fuente: http://developer.android.com/tools/sdk/eclipse-adt.html

Fuente: http://developer.android.com/sdk/installing/installing-adt.html#Download

Introducir publicidad en Apps de Android

En este enlace viene explicado todo el proceso por Google.

Fuente : https://developers.google.com/mobile-ads-sdk/docs/admob/fundamentals?hl=es

Descargar videos de Youtube sin programas

Para poder descargar un video de Youtube solo hay que hacer lo siguiente.
Una vez tenemos la dirección del video:

http://www.youtube.es/direcciondelvideo

Cambiamos http://www. por ss quedando finalmente de la siguiente manera:

ssyoutube.es/direccióndelvideo



lunes, 14 de abril de 2014

Using Screen and Game Classes

There is some confusion about the Game and Screen classes. Part of that may be because the Project Setup tutorial in the official libgdx wiki has you creating a Game class, which is also different than the com.badlogic.gdx.Game class.

Details

When you start developing a libgdx app, you will set up your project to where the Android starter (AndroidApplication class) and/or Desktop starter (LwjglApplication or JoglApplication) projects initialize an ApplicationListener. The ApplicationListener's methods can be managed by using Game and Screen.

com.badlogic.gdx.Game

We create a class that extends Game, which implements ApplicationListener. It will be used as the "Main" libgdx class, the starting point basically, in the core libgdx project. Your create() method is here, and once create() is done it moves on to rendering screens, (the current screen, that is). To switch the current screen, all you need to do is call game.setScreen(screen);

com.badlogic.gdx.Screen

We create our own classes that implement the Screen interface, and use them kind of like mini ApplicationListeners. They have render(), pause(), resume(), and resize(), all called when the ApplicationListener's respective methods would normally be called. They also have other methods- hide() and show().

When setScreen(screen) is called, the current screen's hide() method is called, the new screen becomes the current screen, and its show() method is called. Then the new screen's render() method is called each frame by Game. Only one screen is rendered at a time.

Note that Screen's dispose() method is never called automatically- when ApplicationListener's dispose() method is called, Game calls screen.hide() instead.

Tips

I prefer to keep a single instance of each screen around for the life of the game, so that new Screen objects are not being created every screen change, to avoid garbage collection.

Each Screen should have a reference to your Game, if for no other reason than to switch screens from within a screen.

Game code example

 import com.badlogic.gdx.Game;

public class MyGame extends Game {


        MainMenuScreen mainMenuScreen;
        AnotherScreen anotherScreen;


       @Override
        public void create() {
                mainMenuScreen = new MainMenuScreen(this);
                anotherScreen = new AnotherScreen(this);
                setScreen(mainMenuScreen);              
        }
 }

Screen code example

 import com.badlogic.gdx.Screen;

public class MainMenuScreen implements Screen {


       MyGame game; // Note it's "MyGame" not "Game"


       // constructor to keep a reference to the main Game class
        public MainMenuScreen(MyGame game){
                this.game = game;
        }
        
        @Override
        public void render(float delta) {
                // update and draw stuff
             if (Gdx.input.justTouched()) // use your own criterion here
                 game.setScreen(game.anotherScreen);
        }


       @Override
        public void resize(int width, int height) {
        }


       @Override
        public void show() {
             // called when this screen is set as the screen with game.setScreen();
        }


       @Override
        public void hide() {
             // called when current screen changes from this to a different screen
        }


       @Override
        public void pause() {
        }


       @Override
        public void resume() {
        }


       @Override
        public void dispose() {
                // never called automatically
        }
 }

FUENTE: https://code.google.com/p/libgdx-users/wiki/ScreenAndGameClasses


sábado, 12 de abril de 2014

75 Essential Cheat Sheets for Designers and Programmers

Programming is not an easy job, and requires a lot of concentration and expert reference. You might get struck anytime, anywhere in the code, where you can’t work out the things, but need to finish the code as soon as possible, for your boss sitting hot over your head. At that moment of time, you wish, that something existed that could give you a quick help, or a quick reference, solving your problem in moments, and you get the things to work, as they are supposed to be!  The good news, there exists a tool like this. Not actually a tool, we call them Cheat Sheets.
Cheat sheets are a collection of notes and facts used for quick reference. These are same, like those of the cheat slips, the students used to take during their exams. They had to use the cheat sheet without the instructor’s knowledge, but in the case of programming, you are allowed to use cheat sheets during your coding jobs!
Giving a rough idea, about what a cheat sheet includes, is that it contains the information about all the syntaxes and data properties, that are used in that particular coding language. May it be C, HTML, JAVA,LISP, Haskell, PHP, Python, Ruby, Photoshop, etc you can find cheat sheets for all of the languages easily over the web! These are great tools, and will help you greatly in your programming process, and will ease your job to a great extent!
Here, we have a list of the best 75 cheat sheets for the designers and developers. We call them the best ones, for the fact, these are up to the mark, contain to the point information, and everything shared with them is accurate to all standards. These will wave good bye to your programming cribs, and get your codes working properly with a quick reference lasting for merely a few minutes!

1) Cheat Sheets – jQuery


best free cheat sheets for designers and developers - jquery

2) Cheat Sheets – HTML


best free cheat sheets for designers and developers - html

3) Cheat Sheets - HTML5 Cheat Sheet


best free cheat sheets for designers and developers - HTML5

4) Cheat Sheets – CSS


best free cheat sheets for designers and developers - css

5) Cheat Sheets – CSS2


best free cheat sheets for designers and developers - css2

6) Cheat Sheets – CSS3


best free cheat sheets for designers and developers - css3

7) Cheat Sheets – JavaScript


best free cheat sheets for designers and developers - javascript

8) Cheat Sheets – Linux


best free cheat sheets for designers and developers - linux

9) Cheat Sheets –  Java


best free cheat sheets for designers and developers - java

10) Cheat Sheets - Java 8


best free cheat sheets for designers and developers - java8

11) Cheat Sheets – Perl


best free cheat sheets for designers and developers - perl

12) Cheat Sheets – PHP


best free cheat sheets for designers and developers - php

13) Cheat Sheets – Python


best free cheat sheets for designers and developers - python

14) Cheat Sheets – Ruby


best free cheat sheets for designers and developers - ruby

15) Cheat Sheets – Ruby on Rails


best free cheat sheets for designers and developers - ruby-on-rails

16) Cheat Sheets – Scala Cheat sheets 


best free cheat sheets for designers and developers - scala

17) Cheat Sheets – SQL


best free cheat sheets for designers and developers - sql

18) Cheat Sheets – My SQL


best free cheat sheets for designers and developers - my-sql

19) Cheat Sheets – C#


best free cheat sheets for designers and developers - c#

20) Cheat Sheets – SQLite


best free cheat sheets for designers and developers - sqlite

21) Cheat Sheets – C++


best free cheat sheets for designers and developers - C++

22) Cheat Sheets – Javascript and AJAX 


best free cheat sheets for designers and developers - ajax

23) Cheat Sheets – C


best free cheat sheets for designers and developers - c

24) Cheat Sheets – Unix


best free cheat sheets for designers and developers - unix

25) Cheat Sheets – Ubuntu


best free cheat sheets for designers and developers - ubuntu

26) Cheat Sheets – WordPress


best free cheat sheets for designers and developers - wordpress

27) Cheat Sheets – Nodejs


best free cheat sheets for designers and developers - nodejs

28) Cheat Sheets –  HTML and XHTML


best free cheat sheets for designers and developers - xhtml

29) Cheat Sheets – XML


best free cheat sheets for designers and developers - xml

30) Cheat Sheets – Oracle


best free cheat sheets for designers and developers - oracle

31) Cheat Sheets – NMAP


best free cheat sheets for designers and developers - nmap

32) Cheat Sheets – Mac OS X


best free cheat sheets for designers and developers - macosx

33) Cheat Sheets - Haskell


best free cheat sheets for designers and developers - haskell

34) Cheat Sheets – DOM


best free cheat sheets for designers and developers - dom

35) Cheat Sheets – Drupal


best free cheat sheets for designers and developers - drupal

36) Cheat Sheets – Oracle DB 


best free cheat sheets for designers and developers - oracledb

37) Cheat Sheets – FireFox 


best free cheat sheets for designers and developers - firefox

38) Cheat Sheets – Apache Ant


best free cheat sheets for designers and developers- apacheant

39) Cheat Sheets – Apache hadoop


best free cheat sheets for designers and developers - apache

40)  Cheat Sheets -Git


best free cheat sheets for designers and developers - git

41)  Cheat Sheets -Mathematica


best free cheat sheets for designers and developers - mathmatics

42) Cheat Sheets – RedHat Fedora


best free cheat sheets for designers and developers - fedora

43) Cheat Sheets – Unicode


best free cheat sheets for designers and developers - unicode

44) Cheat Sheets - PostgreSQL


best free cheat sheets for designers and developers - postgresql

45) Cheat Sheets – MATLAB


best free cheat sheets for designers and developers - matlab

46) Cheat Sheets - Design Patterns

47) Cheat Sheets - Django Reference Sheet

48) Cheat Sheets - Flash Quick Reference

49) Cheat Sheets - Fortran

50) Cheat Sheets - Adobe flex 3 cheat sheet

51) Cheat Sheets - Google Chrome Plus

52) Cheat Sheets – HTTP

53) Cheat Sheets - Internet Explorer

54) Cheat Sheets - JavaEE6 Reference Sheet

55) Cheat Sheets – LISP

56) Cheat Sheets - Mootools 1.3 cheat sheets

57) Cheat Sheets - Photoshop

58) Cheat Sheets - Prototype

59) Cheat Sheets – QT

60) Cheat Sheets - Shell Scrip Cheat Sheet

61) Cheat Sheets - Server Side Includes Qucik Reference

62) Cheat Sheets – VBasic Quick Ref

63) Cheat Sheets - ASPCheat Sheet

64) Cheat Sheets - WebGL Reference

65) Cheat Sheets - Microsoft NET

66) Cheat Sheets - Flash ActionScript Quick Ref

67)  Cheat Sheets - BlueprintCSS

68) Cheat Sheets – Computer Science

69) Cheat Sheets - Erlang

70) Cheat Sheets – Java Server faces 

71) Cheat Sheets - JDBC Best Practices

72) Cheat Sheets - Core-ASPNet

73) Cheat Sheets - HTML5 IndexedDB

74) Cheat Sheets - Using XML Java

75) Cheat Sheets - HTML5 Canvas Web Standard