<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>SISTEMAS O.R.P &#187; Uncategorized</title>
	<atom:link href="http://www.sistemasorp.es/category/uncategorized/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.sistemasorp.es</link>
	<description>Blog sobre desarrollos y otros temas</description>
	<lastBuildDate>Sat, 03 Jul 2010 07:15:59 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0</generator>
		<item>
		<title>Compilando programas para la fonera</title>
		<link>http://www.sistemasorp.es/2006/11/11/compilando-programas-para-la-fonera/</link>
		<comments>http://www.sistemasorp.es/2006/11/11/compilando-programas-para-la-fonera/#comments</comments>
		<pubDate>Sat, 11 Nov 2006 08:57:00 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://www.sistemasorp.es/2006/11/11/compilando-programas-para-la-fonera/</guid>
		<description><![CDATA[Hace poco leí un artículo en barrapunto donde descubrí (un poco tarde, ya lo sé) que la fonera tenía ssh (y por ende linux embebido). El caso es que viendo páginas como la de radikalq3 me animé a solicitar a FON su preciado router wireless (cuando aún estaba de oferta a 5 ?) para hacer [...]]]></description>
			<content:encoded><![CDATA[<p>Hace poco leí un <a href="http://barrapunto.com/article.pl?sid=06/11/06/1610230" target="_blank">artículo en barrapunto</a> donde descubrí (un poco tarde, ya lo sé) que la fonera tenía ssh (y por ende linux embebido).</p>
<p>El caso es que viendo páginas como la de <a href="http://fonera.q3.nu/">radikalq3</a> me animé a solicitar a FON su preciado router wireless (cuando aún estaba de oferta a 5 ?) para hacer &#8220;pruebas y experimentos&#8221; y de paso unirme a la comunidad FON.</p>
<p><img src="http://www.quejateportodo.com/blog/fonera.jpg" alt="" /></p>
<p>La recibí ayer, y por supuesto habilité el ssh mediante hardware (cables, condensadores, MAX232 y el puerto serie). Por cierto, una vez listado todo el proceso de arranque el usuario debe pulsar INTRO para activar la consola. Una vez abierto el puerto 22 monté de nuevo la fonera y me conecté por ssh. La primera vez que entras debes entrar como root y con password admin. Posteriormente cambié la clave de root desde la <a href="http://www.fon.com/" target="_blank">web de FON</a> en <span style="font-style:italic;">Configura tu Router Social FON/Contraseña del Router</span></p>
<p>A continuación me bajé los fuentes de la fonera <a href="http://download.fon.com/firmware/fonera/latest/fonera.tar.bz2">http://download.fon.com/firmware/fonera/latest/fonera.tar.bz2</a> (unos noventa megas), los guardé en mi carpeta personal de mi servidor con mandriva 2006, los descomprimí con <span style="font-style:italic;">tar xvjf fonera.tar.bz2</span>, ejecuté <span style="font-style:italic;">make menuconfig</span> sin modificar nada, grabé y posteriormente tecleé <span style="font-style:italic;">make</span>. La primera vez no me compiló, por lo que tuve que instalar varios paquetes: <span style="font-style:italic;">urpmi flex</span>, <span style="font-style:italic;">urpmi bison</span> y <span style="font-style:italic;">urpmi byacc</span>.</p>
<p>Una vez compilados los fuentes ya solo me quedaba saber como poder compilar un programa y subirlo a la fonera. La compilación se explica en la web de OpenWRT:<br />
<a href="http://downloads.openwrt.org/docs/buildroot-documentation.html#using_toolchain" target="_blank">http://downloads.openwrt.org/docs/buildroot-documentation.html#using_toolchain</a>. Así que me puse manos a la obra e hice este programa llamado <span style="font-weight:bold;">prueba.c</span> el cual simplemente abre le fichero <span style="font-style:italic;">/etc/passwd</span> y muestra su contenido (en vez de hacer el típico hola mundo):</p>

<div class="wp_syntax"><div class="code"><pre class="c" style="font-family:monospace;"><span style="color: #339933;">#include &lt;stdio.h&gt;</span>
&nbsp;
<span style="color: #993333;">int</span> main<span style="color: #009900;">&#40;</span><span style="color: #993333;">void</span><span style="color: #009900;">&#41;</span>
<span style="color: #009900;">&#123;</span>
      FILE <span style="color: #339933;">*</span>fichero<span style="color: #339933;">;</span>
      <span style="color: #993333;">char</span> cadena<span style="color: #009900;">&#91;</span><span style="color: #0000dd;">100</span><span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span>
      <span style="color: #b1b100;">if</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#40;</span>fichero<span style="color: #339933;">=</span>fopen<span style="color: #009900;">&#40;</span><span style="color: #ff0000;">&quot;/etc/passwd&quot;</span><span style="color: #339933;">,</span><span style="color: #ff0000;">&quot;r&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">!=</span>NULL<span style="color: #009900;">&#41;</span>
      <span style="color: #009900;">&#123;</span>
              fgets<span style="color: #009900;">&#40;</span>cadena<span style="color: #339933;">,</span><span style="color: #0000dd;">100</span><span style="color: #339933;">,</span>fichero<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
              <span style="color: #b1b100;">while</span><span style="color: #009900;">&#40;</span><span style="color: #339933;">!</span>feof<span style="color: #009900;">&#40;</span>fichero<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span>
              <span style="color: #009900;">&#123;</span>
                      <span style="color: #000066;">printf</span><span style="color: #009900;">&#40;</span>cadena<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
                      fgets<span style="color: #009900;">&#40;</span>cadena<span style="color: #339933;">,</span><span style="color: #0000dd;">100</span><span style="color: #339933;">,</span>fichero<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
              <span style="color: #009900;">&#125;</span>
              fclose<span style="color: #009900;">&#40;</span>fichero<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
      <span style="color: #009900;">&#125;</span>
      <span style="color: #b1b100;">return</span> <span style="color: #0000dd;">0</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p><img src="http://www.quejateportodo.com/blog/servidorssh.jpg" alt="" /></p>
<p>Lo compilé con <span style="font-style:italic;">mips-linux-uclibc-gcc -o prueba prueba.c</span> y se creó un ejecutable sin problemas. A continuación lo moví a /var/www/html para que estuviese disponible a través del servidor web apache y desde la fonera lo recuperé con <span style="font-style:italic;">wget http://192.168.0.11/prueba</span> (notese que la ip del servidor será distinta en vuestro caso), le cambié los permisos para que se pudiera ejecutar <span style="font-style:italic;">chmod 755 prueba</span> y finalmente lo probé funcionado perfectamente.</p>
<p><img src="http://www.quejateportodo.com/blog/fonerassh.jpg" alt="" /></p>
<p>Espero que esto os anime a crear vuestros propios programas. Este ejecutable me ocupó  unos 7 KBytes y aún tengo 7 megas de espacio libre en la fonera para añadirle nuevas cosas <img src='http://www.sistemasorp.es/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p><span style="font-weight:bold;">Actualización 08/02/2007:</span></p>
<p>Dani, un lector del blog me comentó que la fonera solo tiene 4 megas libres de espacio de almacenamiento permanente (y no 7 megas como había escrito en el artículo). Después de hacer dos experimentos que podéis leer en los comentarios de este blog la capacidad real de la fonera con el firmware de FON es de <span style="font-weight:bold;">5 MB</span>. Gracias Dani por forzarme a experimentar <img src='http://www.sistemasorp.es/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' /> </p>
]]></content:encoded>
			<wfw:commentRss>http://www.sistemasorp.es/2006/11/11/compilando-programas-para-la-fonera/feed/</wfw:commentRss>
		<slash:comments>10</slash:comments>
		</item>
		<item>
		<title>Manejar aparatos eléctricos desde el PC: domótica (3/5)</title>
		<link>http://www.sistemasorp.es/2006/03/20/manejar-aparatos-electricos-desde-el-pc-domotica-35/</link>
		<comments>http://www.sistemasorp.es/2006/03/20/manejar-aparatos-electricos-desde-el-pc-domotica-35/#comments</comments>
		<pubDate>Mon, 20 Mar 2006 22:43:00 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://www.sistemasorp.es/2006/03/20/manejar-aparatos-electricos-desde-el-pc-domotica-35/</guid>
		<description><![CDATA[Al estar el sistema de domótica centralizado en un solo programa que escucha por un puerto TCP, se puede ampliar todo lo que sea necesario para cubrir todo tipo de necesidades de comunicación. Una de las posibilidades que ofrece la domótica es poder acceder a los aparatos aún cuando no se está presente en el [...]]]></description>
			<content:encoded><![CDATA[<p>Al estar el sistema de domótica centralizado en un solo programa que escucha por un puerto TCP, se puede ampliar todo lo que sea necesario para cubrir todo tipo de necesidades de comunicación.</p>
<p>Una de las posibilidades que ofrece la domótica es poder acceder a los aparatos aún cuando no se está presente en el hogar. Es por ello que necesitaba un medio por el cual poder acceder al sistema desde fuera de mi casa. Pues bién, aprovechando la infraestructura de Internet, y que el protocolo HTTP es el que esta más extendido, instalé un servidor web en casa e hice un portal al cual pudiera acceder desde cualquier sitio que tuviese acceso a Internet mediante un navegador.</p>
<p><img src="http://www.sistemasorp.net/blog/webprincipal.jpg"></p>
<p>En la imágen se puede observar el punto de entrada a la web. En su momento instalé un IIS e hice toda la programación con DHTML + ASP. Al ser una web se puede acceder a ella mediante proxy (seleccionando la opción de HTML) y sin proxy (seleccionando la opción de Java). El usuario y contraseña usa la misma base de datos de la que tira el programa Luces.</p>
<p><img src="http://www.sistemasorp.net/blog/webhtml.jpg"></p>
<p>La sección de HTML es especial para proxys puesto que en muchos sitios se usan (sobre todo empresas) para compartir una conexión de Internet, mantener un registro de accesos, etc. El problema es que si hay proxy es muy posible que no haya otro medio de conectarse a Internet sin pasar por el y por tanto no pueda hacerse una conexión permanente al servidor. Por ello la interfaz esta diseñada para recibir información cuando se hace la petición http al servidor y no se refresca hasta que no se vuelva a seleccionar otro estado (eligiendo el aparato y pulsando <span style="font-style:italic;">Enviar</span>) o ver el estado actual (pulsando el botón <span style="font-style:italic;">Ver Estado</span>). Si el usuario es administrador, además de poder visualizar los aparatos e interactuar con ellos como otro usuario con permisos, también es capaz de manejar los comandos privilegiados además de poder hacer consultas sql a la base de datos. El fichero ASP es el encargado de hacer la conexión TCP/IP al programa Luces (tanto Luces como el IIS residen en la misma máquina), para ello usé un componente ActiveX llamado vbwinsock y que lo podeis descargar <a href="http://www.15seconds.com/issue/990408.htm" target="_blank">aquí</a>.</p>
<p><img src="http://www.sistemasorp.net/blog/webjava.jpg"></p>
<p>La sección java es similar a la de HTML pero orientada a usuarios que tienen acceso directo a Internet. Se llama así porque la parte donde estan representados los aparátos es un applet de java con conexión directa al servidor de Luces (la seguridad de java solo deja conectarse al mismo dominio desde que se pidió la página). Por ello si pulsamos en cualquiera de los botones se actualiza rápidamente el estado, incluso si otro usuario cambia el estado de alguno de los aparatos también se vería reflejado. Sería como conectarse por telnet pero de una forma mucho más sencilla y amigable.</p>
<p>Ha habido gente que me ha preguntado por qué tardo tanto en escribir entre artículo y artículo, la razón es que tengo poco tiempo y otras veces no tengo ganas de salir del trabajo para ponerme otra vez en frente del ordenador, por eso os pido un poco de paciencia.</p>
<p>Otras personas me han preguntado si voy a dejar accesible el código fuente de las aplicaciones que aquí menciono, y si, efectivamente lo liberaré para que otros puedan hacer soluciones similares o basarse en esta para hacer algo nuevo. Además tengo pensado grabar un video del funcionamiento de todo el sistema de domótica.</p>
<p><a href="http://sistemasorp.blogspot.com/2006/02/manejar-aparatos-elctricos-desde-el-pc_21.html">Manejar aparatos eléctricos desde el PC: domótica (2/5)</a>&nbsp;<a href="http://sistemasorp.blogspot.com/2006/04/manejar-aparatos-elctricos-desde-el-pc.html">Manejar aparatos eléctricos desde el PC: domótica (4/5)</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.sistemasorp.es/2006/03/20/manejar-aparatos-electricos-desde-el-pc-domotica-35/feed/</wfw:commentRss>
		<slash:comments>10</slash:comments>
		</item>
		<item>
		<title>Manejar aparatos eléctricos desde el PC: domótica (2/5)</title>
		<link>http://www.sistemasorp.es/2006/02/21/manejar-aparatos-electricos-desde-el-pc-domotica-25/</link>
		<comments>http://www.sistemasorp.es/2006/02/21/manejar-aparatos-electricos-desde-el-pc-domotica-25/#comments</comments>
		<pubDate>Tue, 21 Feb 2006 11:22:00 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://www.sistemasorp.es/2006/02/21/manejar-aparatos-electricos-desde-el-pc-domotica-25/</guid>
		<description><![CDATA[Para poder controlar el módulo por software se me planteaba una duda, ¿cómo hacer para que varios programas accediesen a este?. Todos tenían que ser ejecutables y ser lanzados con el Port Talk, sin embargo no era lo más optimo porque no había manera de saber que aparatos estaban encendidos y cuales no, además de [...]]]></description>
			<content:encoded><![CDATA[<p>Para poder controlar el módulo por software se me planteaba una duda, ¿cómo hacer para que varios programas accediesen a este?. Todos tenían que ser ejecutables y ser lanzados con el Port Talk, sin embargo no era lo más optimo porque no había manera de saber que aparatos estaban encendidos y cuales no, además de que mi interés era controlar los aparatos no solo desde el propio ordenador donde estaba conectado el módulo, sino también a través de otros dispositivos.</p>
<p>La solución se mostraba por sí sola: solo un programa accedería al módulo y los demás deberían comunicarse con este para lanzarle las peticiones y recibir el estado actual en que se encontraban los aparatos. De ahí salió el programa <span style="font-style:italic;">Luces</span>, el cual era un simple servidor tcp que escuchaba por el puerto 1976 (mi año de nacimiento) y se comunicaba con sus clientes mediante un sencillo protocolo basado en números (al estilo del protocolo simple de transferencia de correo &#8211; SMTP). Los códigos que devuelve el servidor son los siguientes:</p>
<table bgcolor="#8ccb12">
<tr>
<td><span style="font-weight:bold;">100</span></td>
<td>Saludo al nuevo cliente conectado</td>
</tr>
<tr>
<td><span style="font-weight:bold;">101</span></td>
<td>Estado en que se encuentran los aparatos (máscara)</td>
</tr>
<tr>
<td><span style="font-weight:bold;">200</span></td>
<td>Usuario introducido</td>
</tr>
<tr>
<td><span style="font-weight:bold;">201</span></td>
<td>Contraseña introducida</td>
</tr>
<tr>
<td><span style="font-weight:bold;">202</span></td>
<td>Permitir o denegar peticiones, cerrar programa o apagar equipo</td>
</tr>
<tr>
<td><span style="font-weight:bold;">300</span></td>
<td>Estado no identificado</td>
</tr>
<tr>
<td><span style="font-weight:bold;">301</span></td>
<td>Comando no reconocido</td>
</tr>
<tr>
<td><span style="font-weight:bold;">302</span></td>
<td>Fallo en la autentificación</td>
</tr>
</table>
<p>Por su parte el cliente envia los siguientes comandos (en mayúsculas o en minúsculas):</p>
<table bgcolor="#ffb400">
<tr>
<td><span style="font-weight:bold;">USER:</span>&lt;usuario&gt;</td>
<td>Usuario a validar</td>
</tr>
<tr>
<td><span style="font-weight:bold;">PASS:</span>&lt;contraseña&gt;</td>
<td>Contraseña a validar</td>
</tr>
<tr>
<td><span style="font-weight:bold;">&lt;Número&gt;</span></td>
<td>Estado que se quiere aplicar a los aparatos (máscara)</td>
</tr>
<tr>
<td><span style="font-weight:bold;">OPEN</span></td>
<td>Permite a los usuarios no administradores manejar los aparatos</td>
</tr>
<tr>
<td><span style="font-weight:bold;">CLOSE</span></td>
<td>Deniega a los usuarios no administradores manejar los aparatos</td>
</tr>
<tr>
<td><span style="font-weight:bold;">QUIT</span></td>
<td>Cierra la aplicación</td>
</tr>
<tr>
<td><span style="font-weight:bold;">BYE</span></td>
<td>Apaga el equipo</td>
</tr>
</table>
<p>En primer lugar el orden que se debe seguir es:</p>
<p><span style="font-style:italic;">Servidor</span>: Mensaje de Saludo.<br /><span style="font-style:italic;">Cliente</span>: Enviar USER: y el nombre de usuario.<br /><span style="font-style:italic;">Servidor</span>: Mensaje de Usuario Introducido.<br /><span style="font-style:italic;">Cliente</span>: Enviar PASS: y la contraseña del usuario.<br /><span style="font-style:italic;">Servidor</span>: Mensaje de Contraseña Introducida.</p>
<ul>
<li>Si el usuario introduce una contraseña incorrecta el servidor le mostrará un fallo en la autentificación (302) y cerrará la conexión.</li>
<li>Si el usuario introduce un comando no reconocido cuando se está validando el servidor le mostrará un comando no reconocido (301) y le cerrará la conexión, en cambio cuando este validado solo le mostrará el estado de los aparatos (101).</li>
<li>Si el usuario introduce antes el comando PASS que el USER el servidor le mostrará estado no identificado (300) y le cerrará la conexión.</li>
<p></ul>
<p>En segundo lugar cuando el usuario ya esta validado puede introducir o bién los comandos <span style="font-style:italic;">OPEN</span>, <span style="font-style:italic;">CLOSE</span>, <span style="font-style:italic;">QUIT</span> y <span style="font-style:italic;">BYE</span>; o bién un número de 0 a 15 que actuaría como máscara para encender o apagar los aparatos (si el número es mayor que 15 se usa el módulo de 16).</p>
<p>Haciendo un telnet, lo anterior comentado se vería de la siguiente forma:<br /><img src="http://www.sistemasorp.net/blog/telnetdomo1.jpg"></p>
<p>Y en la aplicación Luces se vería así:<br /><img src="http://www.sistemasorp.net/blog/lucesdomo1.jpg"></p>
<p>Si ahora cometemos un error (por ejemplo metemos mal el usuario) el resultado quedaría así:<br /><img src="http://www.sistemasorp.net/blog/telnetdomo2.jpg"><br /><img src="http://www.sistemasorp.net/blog/lucesdomo2.jpg"></p>
<p>Como se puede observar, la segunda conexión la he hecho a través de otro ordenador. Gracias a que se usa el protocolo el tcp/ip se puede conectar desde cualquier programa (independientemente del sistema operativo, arquitectura de ordenador, etc).</p>
<p>Por otro lado el sistema se basa en una base de datos para gestionar los usuarios, los eventos y los aparatos:</p>
<p><img src="http://www.sistemasorp.net/blog/derdomo.jpg"></p>
<p>En mi caso usé una base de datos access, pero como es lógico pensar, se puede usar cualquier tipo de base de datos relacional. Las tablas son sólo 4 y se detallan a continuación:</p>
<table bgcolor="#cb93f6">
<tr bgcolor="#fffebc">
<td><span style="font-weight:bold;">tblUsuarios</span></td>
<td>Donde se almacenan los usuarios del sistema y sus permisos</td>
</tr>
<tr>
<td><span style="font-weight:bold;">intID</span></td>
<td>Autonúmerico (o secuencia) que identifica al usuario inequivocamente</td>
</tr>
<tr>
<td><span style="font-weight:bold;">strNombre</span></td>
<td>Nombre del usuario</td>
</tr>
<tr>
<td><span style="font-weight:bold;">strApellidos</span></td>
<td>Apellido o apellidos del usuario</td>
</tr>
<tr>
<td><span style="font-weight:bold;">strLogin</span></td>
<td>Identificador del usuario para validarse en el sistema</td>
</tr>
<tr>
<td><span style="font-weight:bold;">strPassword</span></td>
<td>Contraseña del usuario para validarse en el sistema</td>
</tr>
<tr>
<td><span style="font-weight:bold;">blnActivo</span></td>
<td>Bandera que indica si un usuario puede validarse en el sistema o no</td>
</tr>
<tr>
<td><span style="font-weight:bold;">bytNivel</span></td>
<td>Nivel del usuario (100 administrador, 50 usuario normal, 0 visitante)</td>
</tr>
<tr>
<td><span style="font-weight:bold;">bytMascara</span></td>
<td>Máscara de permiso para aparatos: Si el usuario tiene por ejemplo 10 (1010 en binario) sólo puede utilizar los aparatos 2 y 4, en cambio los aparatos 1 y 3 únicamente puede ver su estado</td>
</tr>
</table>
<table bgcolor="#cb93f6">
<tr bgcolor="#fffebc">
<td><span style="font-weight:bold;">tblAcciones</span></td>
<td>Donde se almacenan las distintas acciones del usuario</td>
</tr>
<tr>
<td><span style="font-weight:bold;">bytID</span></td>
<td>Autonúmerico (o secuencia) que identifica la acción inequivocamente</td>
</tr>
<tr>
<td><span style="font-weight:bold;">strAccion</span></td>
<td>Nombre de la acción (Usuario Validado, Usuario Desconectado, Orden y Comando)</td>
</tr>
</table>
<table bgcolor="#cb93f6">
<tr bgcolor="#fffebc">
<td><span style="font-weight:bold;">tblLog</span></td>
<td>Donde se almacena la actividad que lleva a cabo el usuario</td>
</tr>
<tr>
<td><span style="font-weight:bold;">intID</span></td>
<td>Autonúmerico (o secuencia) que identifica la acción del usuario</td>
</tr>
<tr>
<td><span style="font-weight:bold;">intUsuario</span></td>
<td>Campo relacionado con el intID de la tabla tblUsuarios</td>
</tr>
<tr>
<td><span style="font-weight:bold;">bytAccion</span></td>
<td>Campo relacionado con el bytID de la tabla tblAcciones</td>
</tr>
<tr>
<td><span style="font-weight:bold;">datFecha</span></td>
<td>Fecha y hora de la acción</td>
</tr>
<tr>
<td><span style="font-weight:bold;">strIP</span></td>
<td>IP de la máquina donde se ordenó la acción</td>
</tr>
<tr>
<td><span style="font-weight:bold;">strDescripcion</span></td>
<td>Descripción de la acción</td>
</tr>
</table>
<table bgcolor="#cb93f6">
<tr bgcolor="#fffebc">
<td><span style="font-weight:bold;">tblAparatos</span></td>
<td>Donde se almacenan los nombres de los aparatos a manejar</td>
</tr>
<tr>
<td><span style="font-weight:bold;">intID</span></td>
<td>Autonúmerico (o secuencia) que identifica el aparato inequivocamente</td>
</tr>
<tr>
<td><span style="font-weight:bold;">strNombre</span></td>
<td>Nombre del aparato</td>
</tr>
</table>
<p><a href="http://sistemasorp.blogspot.com/2006/02/manejar-aparatos-elctricos-desde-el-pc.html">Manejar aparatos eléctricos desde el PC: domótica (1/5)</a> <a href="http://sistemasorp.blogspot.com/2006/03/manejar-aparatos-elctricos-desde-el-pc.html">Manejar aparatos eléctricos desde el PC: domótica (3/5)</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.sistemasorp.es/2006/02/21/manejar-aparatos-electricos-desde-el-pc-domotica-25/feed/</wfw:commentRss>
		<slash:comments>8</slash:comments>
		</item>
		<item>
		<title>PC a móvil a PC</title>
		<link>http://www.sistemasorp.es/2006/01/26/pc-a-movil-a-pc/</link>
		<comments>http://www.sistemasorp.es/2006/01/26/pc-a-movil-a-pc/#comments</comments>
		<pubDate>Thu, 26 Jan 2006 22:07:00 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://www.sistemasorp.es/2006/01/26/pc-a-movil-a-pc/</guid>
		<description><![CDATA[Hace un tiempo desarrollé un gateway sms/mail/sms donde además del software, la pieza clave era esta: El gateway esta dado de baja (tuvo demasiado éxito), sin embargo el móvil que aparece en la imágen lo sigo usando en algunos de mis proyectos (pronto sabreis por qué estoy escribiendo artículos sobre aparatos). Se trata de un [...]]]></description>
			<content:encoded><![CDATA[<p>Hace un tiempo desarrollé un <a href="http://sistemasorp.blogspot.com/2005/04/gateway-smsemailsms.html" target="_blank">gateway sms/mail/sms</a> donde además del software, la pieza clave era esta:</p>
<p><img src="http://www.sistemasorp.net/blog/movilgsm.jpg" alt="" /></p>
<p>El gateway esta dado de baja (tuvo demasiado éxito), sin embargo el móvil que aparece en la imágen lo sigo usando en algunos de mis proyectos (pronto sabreis por qué estoy escribiendo artículos sobre aparatos). Se trata de un siemens m35i que en su día me cargué la pantalla y lo destiné como modem gsm para poder enviar y recibir sms. Este se comunica con un cable de datos por el puerto serie con el ordenador. Como el cable tiene que usar el mismo compartimento que la fuente de alimentación del móvil y necesitaba tener los dos al mismo tiempo, conecté los pines donde se conecta la batería del móvil a un pequeño circuito con un L7805C y dos condensadores, funcionando todo ello con una fuente de alimentación de 12 voltios.</p>
<p>En este caso el móvil al ser un modem gsm (como la inmensa mayoría) se puede manejar con <a href="http://en.wikipedia.org/wiki/Hayes_AT_command_set" target="_blank">comandos AT</a>, aunque algunos son característicos de los móviles (como el de mandar sms).</p>
<p>Para trabajar con el, en mi caso, tengo que abrir el puerto serie a 19200 baudios, 8 bits, ninguna paridad y un bit de stop.</p>
<p><img src="http://www.sistemasorp.net/blog/hyperterminal.jpg" alt="" /></p>
<p>En mi caso, siempre me interesa usarlo como transmisor/receptor de sms, por lo que leyendo un poco la <a href="http://www.dhservis.cz/docs_soubory/at_pro_c35i-gsm_07.07_a_07.05.pdf" target="_blank">documentación del móvil</a> veo que para enviar sms se usa el comando <span style="font-weight:bold;">AT+CMGS</span>. Sin embargo mi móvil no permite mensajes de texto de forma directa, sino que necesita enviarlos en <a href="http://www.dreamfabric.com/sms/" target="_blank">formato estandar PDU</a> (también cuando muestra los recibidos). Buscando por ahí no he encontrado mucho código fuente (en java <a href="http://www.wrankl.de/SMST/SMST.html" target="_blank">smstools</a>) por lo que me hice una rutina en C para pasar de texto a PDU y viceversa:</p>

<div class="wp_syntax"><div class="code"><pre class="c" style="font-family:monospace;"><span style="color: #808080; font-style: italic;">/* Transforma un texto normal (pchOriginal) en PDU (pchTransformado) devolviendo pchTransformado*/</span>
<span style="color: #993333;">char</span> <span style="color: #339933;">*</span>formatoMensaje<span style="color: #009900;">&#40;</span><span style="color: #993333;">char</span> <span style="color: #339933;">*</span>pchOriginal<span style="color: #339933;">,</span> <span style="color: #993333;">char</span> <span style="color: #339933;">*</span>pchTransformado<span style="color: #009900;">&#41;</span>
<span style="color: #009900;">&#123;</span> 
    <span style="color: #993333;">char</span> pchTablaHex<span style="color: #009900;">&#91;</span><span style="color: #009900;">&#93;</span><span style="color: #339933;">=</span><span style="color: #009900;">&#123;</span><span style="color: #ff0000;">'0'</span><span style="color: #339933;">,</span><span style="color: #ff0000;">'1'</span><span style="color: #339933;">,</span><span style="color: #ff0000;">'2'</span><span style="color: #339933;">,</span><span style="color: #ff0000;">'3'</span><span style="color: #339933;">,</span><span style="color: #ff0000;">'4'</span><span style="color: #339933;">,</span><span style="color: #ff0000;">'5'</span><span style="color: #339933;">,</span><span style="color: #ff0000;">'6'</span><span style="color: #339933;">,</span><span style="color: #ff0000;">'7'</span><span style="color: #339933;">,</span><span style="color: #ff0000;">'8'</span><span style="color: #339933;">,</span><span style="color: #ff0000;">'9'</span><span style="color: #339933;">,</span><span style="color: #ff0000;">'A'</span><span style="color: #339933;">,</span><span style="color: #ff0000;">'B'</span><span style="color: #339933;">,</span><span style="color: #ff0000;">'C'</span><span style="color: #339933;">,</span><span style="color: #ff0000;">'D'</span><span style="color: #339933;">,</span><span style="color: #ff0000;">'E'</span><span style="color: #339933;">,</span><span style="color: #ff0000;">'F'</span><span style="color: #009900;">&#125;</span><span style="color: #339933;">;</span>
    <span style="color: #993333;">unsigned</span> <span style="color: #993333;">char</span> chrCaracter<span style="color: #339933;">;</span> 
    <span style="color: #993333;">int</span> intContador<span style="color: #339933;">;</span> 
    <span style="color: #993333;">int</span> intIndice<span style="color: #339933;">;</span> 
    <span style="color: #993333;">int</span> intTamano<span style="color: #339933;">;</span> 
    <span style="color: #993333;">int</span> intMascara<span style="color: #339933;">;</span> 
    <span style="color: #993333;">int</span> intDesplaza<span style="color: #339933;">;</span>
&nbsp;
    intTamano <span style="color: #339933;">=</span> strlen<span style="color: #009900;">&#40;</span>pchOriginal<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span> 
    intMascara <span style="color: #339933;">=</span> <span style="color: #0000dd;">1</span><span style="color: #339933;">;</span> 
    intContador <span style="color: #339933;">=</span> <span style="color: #0000dd;">0</span><span style="color: #339933;">;</span> 
    intIndice <span style="color: #339933;">=</span> <span style="color: #0000dd;">2</span><span style="color: #339933;">;</span> 
    strcpy<span style="color: #009900;">&#40;</span>pchTransformado<span style="color: #339933;">,</span><span style="color: #ff0000;">&quot;00&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span> 
    intDesplaza <span style="color: #339933;">=</span> <span style="color: #0000dd;">7</span><span style="color: #339933;">;</span>
&nbsp;
    <span style="color: #b1b100;">while</span><span style="color: #009900;">&#40;</span>intContador <span style="color: #339933;">&lt;</span> intTamano<span style="color: #009900;">&#41;</span> 
    <span style="color: #009900;">&#123;</span>  
        chrCaracter <span style="color: #339933;">=</span> <span style="color: #009900;">&#40;</span><span style="color: #009900;">&#40;</span><span style="color: #339933;">*</span><span style="color: #009900;">&#40;</span>pchOriginal <span style="color: #339933;">+</span> intContador <span style="color: #339933;">+</span> <span style="color: #0000dd;">1</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">&amp;</span> intMascara<span style="color: #009900;">&#41;</span> <span style="color: #339933;">&lt;&lt;</span> intDesplaza<span style="color: #009900;">&#41;</span> <span style="color: #339933;">+</span> <span style="color: #009900;">&#40;</span><span style="color: #339933;">*</span><span style="color: #009900;">&#40;</span>pchOriginal <span style="color: #339933;">+</span> intContador<span style="color: #009900;">&#41;</span> <span style="color: #339933;">&gt;&gt;</span> <span style="color: #009900;">&#40;</span><span style="color: #0000dd;">7</span> <span style="color: #339933;">-</span> intDesplaza<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>  
        pchTransformado<span style="color: #009900;">&#91;</span>intIndice<span style="color: #009900;">&#93;</span> <span style="color: #339933;">=</span> pchTablaHex<span style="color: #009900;">&#91;</span><span style="color: #009900;">&#40;</span>chrCaracter <span style="color: #339933;">&amp;</span> <span style="color: #208080;">0xF0</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">&gt;&gt;</span> <span style="color: #0000dd;">4</span><span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span>  
        intIndice<span style="color: #339933;">++;</span>  
        pchTransformado<span style="color: #009900;">&#91;</span>intIndice<span style="color: #009900;">&#93;</span> <span style="color: #339933;">=</span> pchTablaHex<span style="color: #009900;">&#91;</span>chrCaracter <span style="color: #339933;">&amp;</span> <span style="color: #208080;">0x0F</span><span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span>  
        intIndice<span style="color: #339933;">++;</span>  
        intContador<span style="color: #339933;">++;</span>  
        intMascara <span style="color: #339933;">&lt;&lt;=</span> <span style="color: #0000dd;">1</span><span style="color: #339933;">;</span>  
        intMascara<span style="color: #339933;">++</span> <span style="color: #339933;">;</span>  
        intDesplaza<span style="color: #339933;">--;</span>  
        <span style="color: #b1b100;">if</span><span style="color: #009900;">&#40;</span>intDesplaza <span style="color: #339933;">==</span> <span style="color: #339933;">-</span><span style="color: #0000dd;">1</span><span style="color: #009900;">&#41;</span>  
        <span style="color: #009900;">&#123;</span>   
            intMascara <span style="color: #339933;">=</span> <span style="color: #0000dd;">1</span><span style="color: #339933;">;</span>   
            intDesplaza <span style="color: #339933;">=</span> <span style="color: #0000dd;">7</span><span style="color: #339933;">;</span>   
            intIndice <span style="color: #339933;">-=</span> <span style="color: #0000dd;">2</span><span style="color: #339933;">;</span>  
        <span style="color: #009900;">&#125;</span> 
    <span style="color: #009900;">&#125;</span>
&nbsp;
    pchTransformado<span style="color: #009900;">&#91;</span>intIndice<span style="color: #009900;">&#93;</span> <span style="color: #339933;">=</span> <span style="color: #ff0000;">''</span><span style="color: #339933;">;</span>
&nbsp;
    chrCaracter<span style="color: #339933;">=</span><span style="color: #009900;">&#40;</span><span style="color: #993333;">char</span><span style="color: #009900;">&#41;</span>intTamano<span style="color: #339933;">;</span> 
    pchTransformado<span style="color: #009900;">&#91;</span><span style="color: #0000dd;">0</span><span style="color: #009900;">&#93;</span> <span style="color: #339933;">=</span> pchTablaHex<span style="color: #009900;">&#91;</span><span style="color: #009900;">&#40;</span>chrCaracter <span style="color: #339933;">&amp;</span> <span style="color: #208080;">0xF0</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">&gt;&gt;</span> <span style="color: #0000dd;">4</span><span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span> 
    pchTransformado<span style="color: #009900;">&#91;</span><span style="color: #0000dd;">1</span><span style="color: #009900;">&#93;</span> <span style="color: #339933;">=</span> pchTablaHex<span style="color: #009900;">&#91;</span>chrCaracter <span style="color: #339933;">&amp;</span> <span style="color: #208080;">0x0F</span><span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span>
&nbsp;
    <span style="color: #b1b100;">return</span> pchTransformado<span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span>
&nbsp;
<span style="color: #808080; font-style: italic;">/* Transforma un texto PDU (pchOriginal) en texto normal (pchTransformado) devolviendo pchTransformado*/</span>
<span style="color: #993333;">char</span> <span style="color: #339933;">*</span>decodificaMensaje<span style="color: #009900;">&#40;</span><span style="color: #993333;">char</span> <span style="color: #339933;">*</span>pchOriginal<span style="color: #339933;">,</span> <span style="color: #993333;">char</span> <span style="color: #339933;">*</span>pchTransformado<span style="color: #009900;">&#41;</span>
<span style="color: #009900;">&#123;</span> 
    <span style="color: #993333;">char</span> pchLetras<span style="color: #009900;">&#91;</span><span style="color: #0000dd;">5</span><span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span>
    <span style="color: #993333;">unsigned</span> <span style="color: #993333;">char</span> chrCaracter<span style="color: #339933;">;</span> 
    <span style="color: #993333;">int</span> intTamano<span style="color: #339933;">;</span> 
    <span style="color: #993333;">int</span> intContador<span style="color: #339933;">;</span> 
    <span style="color: #993333;">int</span> intArrastre<span style="color: #339933;">;</span> 
    <span style="color: #993333;">int</span> intDesplaza<span style="color: #339933;">;</span> 
    <span style="color: #993333;">int</span> intIndice<span style="color: #339933;">;</span> 
    <span style="color: #993333;">int</span> intMascara<span style="color: #339933;">;</span>
&nbsp;
    intMascara <span style="color: #339933;">=</span> <span style="color: #0000dd;">128</span><span style="color: #339933;">;</span> 
    intIndice <span style="color: #339933;">=</span> intContador <span style="color: #339933;">=</span> intArrastre <span style="color: #339933;">=</span> intDesplaza <span style="color: #339933;">=</span> <span style="color: #0000dd;">0</span><span style="color: #339933;">;</span>
&nbsp;
    strcpy<span style="color: #009900;">&#40;</span>pchLetras<span style="color: #339933;">,</span> <span style="color: #ff0000;">&quot;0x&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span> 
    strncat<span style="color: #009900;">&#40;</span>pchLetras<span style="color: #339933;">,</span> pchOriginal <span style="color: #339933;">+</span> intIndice<span style="color: #339933;">,</span> <span style="color: #0000dd;">2</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span> 
    sscanf<span style="color: #009900;">&#40;</span>pchLetras<span style="color: #339933;">,</span> <span style="color: #ff0000;">&quot;%x&quot;</span><span style="color: #339933;">,</span> <span style="color: #339933;">&amp;</span>intTamano<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
    intIndice <span style="color: #339933;">+=</span> <span style="color: #0000dd;">2</span><span style="color: #339933;">;</span>
&nbsp;
    <span style="color: #b1b100;">while</span><span style="color: #009900;">&#40;</span>intContador <span style="color: #339933;">&lt;</span> intTamano<span style="color: #009900;">&#41;</span> 
    <span style="color: #009900;">&#123;</span>  
        strcpy<span style="color: #009900;">&#40;</span>pchLetras<span style="color: #339933;">,</span> <span style="color: #ff0000;">&quot;0x&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>  
        strncat<span style="color: #009900;">&#40;</span>pchLetras<span style="color: #339933;">,</span> pchOriginal <span style="color: #339933;">+</span> intIndice<span style="color: #339933;">,</span> <span style="color: #0000dd;">2</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>  
        sscanf<span style="color: #009900;">&#40;</span>pchLetras<span style="color: #339933;">,</span> <span style="color: #ff0000;">&quot;%x&quot;</span><span style="color: #339933;">,</span> <span style="color: #339933;">&amp;</span>chrCaracter<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>  
        pchTransformado<span style="color: #009900;">&#91;</span>intContador<span style="color: #009900;">&#93;</span> <span style="color: #339933;">=</span> <span style="color: #009900;">&#40;</span><span style="color: #009900;">&#40;</span>chrCaracter <span style="color: #339933;">&amp;</span> ~intMascara<span style="color: #009900;">&#41;</span> <span style="color: #339933;">&lt;&lt;</span> intDesplaza<span style="color: #009900;">&#41;</span> <span style="color: #339933;">+</span> intArrastre<span style="color: #339933;">;</span>  
        intArrastre<span style="color: #339933;">=</span><span style="color: #009900;">&#40;</span>chrCaracter <span style="color: #339933;">&amp;</span> intMascara<span style="color: #009900;">&#41;</span> <span style="color: #339933;">&gt;&gt;</span> <span style="color: #009900;">&#40;</span><span style="color: #0000dd;">7</span> <span style="color: #339933;">-</span> intDesplaza<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>  
        intIndice <span style="color: #339933;">+=</span> <span style="color: #0000dd;">2</span><span style="color: #339933;">;</span>  
        intMascara <span style="color: #339933;">&gt;&gt;=</span> <span style="color: #0000dd;">1</span><span style="color: #339933;">;</span>  
        intMascara <span style="color: #339933;">+=</span> <span style="color: #0000dd;">128</span><span style="color: #339933;">;</span>  
        intDesplaza<span style="color: #339933;">++;</span>  
        <span style="color: #b1b100;">if</span><span style="color: #009900;">&#40;</span>intMascara <span style="color: #339933;">==</span> <span style="color: #0000dd;">255</span><span style="color: #009900;">&#41;</span>  
        <span style="color: #009900;">&#123;</span>   
            intContador<span style="color: #339933;">++;</span>   
            pchTransformado<span style="color: #009900;">&#91;</span>intContador<span style="color: #009900;">&#93;</span> <span style="color: #339933;">=</span> chrCaracter <span style="color: #339933;">&gt;&gt;</span> <span style="color: #0000dd;">1</span><span style="color: #339933;">;</span>   
            intMascara <span style="color: #339933;">=</span> <span style="color: #0000dd;">128</span><span style="color: #339933;">;</span>   
            intDesplaza <span style="color: #339933;">=</span> intArrastre <span style="color: #339933;">=</span> <span style="color: #0000dd;">0</span><span style="color: #339933;">;</span>  
        <span style="color: #009900;">&#125;</span>
        <span style="color: #339933;">++</span>intContador<span style="color: #339933;">;</span> 
    <span style="color: #009900;">&#125;</span>
&nbsp;
    pchTransformado<span style="color: #009900;">&#91;</span>intContador<span style="color: #009900;">&#93;</span> <span style="color: #339933;">=</span> <span style="color: #ff0000;">''</span><span style="color: #339933;">;</span>
&nbsp;
    <span style="color: #b1b100;">return</span> pchTransformado<span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

]]></content:encoded>
			<wfw:commentRss>http://www.sistemasorp.es/2006/01/26/pc-a-movil-a-pc/feed/</wfw:commentRss>
		<slash:comments>28</slash:comments>
		</item>
		<item>
		<title>Recuperar los títulos de las canciones de un CD con FREEDB</title>
		<link>http://www.sistemasorp.es/2005/11/06/recuperar-los-titulos-de-las-canciones-de-un-cd-con-freedb/</link>
		<comments>http://www.sistemasorp.es/2005/11/06/recuperar-los-titulos-de-las-canciones-de-un-cd-con-freedb/#comments</comments>
		<pubDate>Sun, 06 Nov 2005 22:03:00 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://www.sistemasorp.es/2005/11/06/recuperar-los-titulos-de-las-canciones-de-un-cd-con-freedb/</guid>
		<description><![CDATA[Desde hace mucho tiempo estan disponibles dos servicios en Internet cuyo cometido es almacenar una gigantesca base de datos con los títulos de las canciones de cualquier CD de música que se haya editado. La primera es Gracenote (también conocida antes del 2000 por cddb), de la cual no hablaremos en este artículo por requerir [...]]]></description>
			<content:encoded><![CDATA[<p>Desde hace mucho tiempo estan disponibles dos servicios en Internet cuyo cometido es almacenar una gigantesca base de datos con los títulos de las canciones de cualquier CD de música que se haya editado. La primera es <a href="http://www.gracenote.com/" target="_blank">Gracenote</a> (también conocida antes del 2000 por cddb), de la cual no hablaremos en este artículo por requerir licencia. La segunda es <a href="http://www.freedb.org/" target="_blank">freedb</a> la cual sigue siendo gratuita y con una simple página web podemos consultar la información que nos interesa. En la sección <em>developers</em> podreis encontrar la información necesaria para trabajar con esta tecnología.</p>
<p>Básicamente consiste en obtener una identificación única a partir de la información de la tabla de contenidos de un CD (<em>TOC</em>). Una vez obtenida la identificación, solo hay que hacer una petición web al servidor de freedb con la misma para que nos devuelva el título del CD y la lista de títulos de canciones y sus respectivos autores de las distintas pistas que conforman el CD.</p>
<p>El algoritmo para hallar el identificador único consiste en:<br />
-Sumar los números en segundos de lo que dura cada pista. Es decir, si una cancion dura 4:17, entónces son 257 segundos, luego la suma es 2+5+7=14.<br />
-Una vez obtenido el sumatorio de todas las pistas con el anterior algoritmo, se le saca el módulo de 255 y a continuación se le multiplica por 16777216 (2^24); a este resultado se le suma el tiempo total del CD multiplicado por 256 (2^8) y finalmente a este resultado se le suma el número total de pistas que contiene el CD.</p>
<p>Una vez hallado el identificador único, se transforma a un número hexadecimal y se hace una peticion a <em>freedb</em> de la siguiente manera:</p>
<p>http://freedb.freedb.org/~cddb/cddb.cgi?cmd=cddb+read+misc+&lt;ID UNICO&gt;&amp;hello=name+host.com+appname+1.0&amp;proto=1</p>
<p><em>cddb read misc &lt;ID UNICO&gt;</em> del parámetro <strong>cmd</strong> es el comando que indica que estamos haciendo una petición a la base de datos con el <em>ID UNICO</em>. Por ejemplo <em>cddb read misc c510910d</em>.</p>
<p><em>name host.com appname 1.0</em> del parámetro <strong>hello</strong> indica que persona, dominio, aplicación y versión de la misma esta solicitando la información. Por ejemplo: <em>sistemasorp sistemasorp.blogspot.com testeoCDDB 1.0</em>.</p>
<p>Y finalmente el <em>1</em> del parámetro <strong>proto</strong> indica que versión del protocolo queremos usar para hacer la petición a la base de datos, devolviendonos acorde a la versión una información formateada.</p>
<p>Así por ejemplo si lanzamos esta petición:</p>
<p><a href="http://freedb.freedb.org/~cddb/cddb.cgi?cmd=cddb+read+misc+c510910d&amp;hello=sistemasorp+sistemasorp.blogspot.com+testeoCDDB+1.0&amp;proto=1" target="_blank">http://freedb.freedb.org/~cddb/cddb.cgi?cmd=cddb+read+misc+c510910d&amp;hello=sistemasorp+sistemasorp.blogspot.com+testeoCDDB+1.0&amp;proto=1</a></p>
<p>Nos devuelve lo siguiente (terminado en una linea con un punto, al estilo del <a href="http://es.wikipedia.org/wiki/SMTP" target="_blank">SMTP</a>):</p>
<blockquote><p>210 misc c510910d CD database entry follows (until terminating `.&#8217;)<br />
# xmcd CD database file<br />
#<br />
# Track frame offsets:<br />
# 150<br />
# 24460<br />
# 45650<br />
# 71127<br />
# 98425<br />
# 118997<br />
# 146585<br />
# 164707<br />
# 188897<br />
# 216340<br />
# 240932<br />
# 271642<br />
# 297722<br />
#<br />
# Disc length: 4243 seconds<br />
#<br />
# Revision: 2<br />
# Processed by: cddbd v1.5PL3 Copyright (c) Steve Scherf et al.<br />
# Submitted via: CDex 1.40Beta9<br />
#<br />
DISCID=c510910d<br />
DTITLE=Various / Rave Massacre [Disk 1]<br />
TTITLE0=Raving Bastards &#8211; Love Time<br />
TTITLE1=Chill&#8217;n Force &#8211; Move Raver (Kemo Mix)<br />
TTITLE2=M.A.F. X-Perience &#8211; Dreamland<br />
TTITLE3=Society for Psychical Research &#8211; Silversky<br />
TTITLE4=Obsessiv &#8211; Tune In, Tune On, Drop Out<br />
TTITLE5=Nettuno &#8211; I Cry<br />
TTITLE6=Razor &#8211; Is It Love<br />
TTITLE7=Sunbeam &#8211; Outside World<br />
TTITLE8=Raver&#8217;s Nature &#8211; Tricky Symphony<br />
TTITLE9=NIP Collective &#8211; I&#8217;m About<br />
TTITLE10=RBM &#8211; Banyo Love<br />
TTITLE11=Paranoia X &#8211; Party Program<br />
TTITLE12=NR-Gizer &#8211; Raving Generation<br />
EXTD= YEAR: 1994 ID3G: 31<br />
EXTT0=<br />
EXTT1=<br />
EXTT2=<br />
EXTT3=<br />
EXTT4=<br />
EXTT5=<br />
EXTT6=<br />
EXTT7=<br />
EXTT8=<br />
EXTT9=<br />
EXTT10=<br />
EXTT11=<br />
EXTT12=<br />
PLAYORDER=<br />
.</p></blockquote>
<p>Donde entre comentarios (con la almohadilla delante) da información sobre el disco, copyright y demás; continuando con una lista de parejas nombre/valor que contienen la información que queremos:</p>
<p><strong>DISCID</strong>: El mismo identificador de disco que le hemos pasado<br />
<strong>DTITLE</strong>: El autor y título del CD<br />
<strong>TTITLEX</strong>: El título de canción que está en la pista X<br />
<strong>EXTD</strong>: Información extendida sobre el disco<br />
<strong>EXTTX</strong>: Información extendida sobre la canción que está en la pista X<br />
<strong>PLAYORDER</strong>: El orden en el que se deberían reproducir las pistas<br />
<strong>YEAR</strong>: El año de edición del disco<br />
<strong>ID3G</strong>: La categoría o clase de música que contiene el CD</p>
<p>A continuación expongo dos codigos fuentes (el primero para windows y el segundo para linux) que muestran como recoger el identificador único de un cd y a continuación solicitar la información de ese cd a freedb. Ambos se ejecutan en la consola de texto pasandoles como parámetro la unidad o dispositivo de cd.</p>
<p><strong>WINDOWS</strong>(<a href="http://www.quejateportodo.com/blog/toc.zip">ejecutable y fuentes</a>)</p>

<div class="wp_syntax"><div class="code"><pre class="c" style="font-family:monospace;"><span style="color: #339933;">#include &quot;stdafx.h&quot;</span>
<span style="color: #339933;">#include &lt;stdio.h&gt;</span>
<span style="color: #339933;">#include &lt;stdlib.h&gt;</span>
<span style="color: #339933;">#include &lt;string.h&gt;</span>
<span style="color: #339933;">#include &lt;winsock.h&gt;</span>
<span style="color: #339933;">#include &lt;windows.h&gt;</span>
&nbsp;
<span style="color: #339933;">#define IOCTL_CDROM_READ_TOC 0x00024000</span>
&nbsp;
<span style="color: #993333;">typedef</span> <span style="color: #993333;">struct</span> <span style="color: #009900;">&#123;</span>
  UCHAR  Reserved<span style="color: #339933;">;</span>
  UCHAR  Control <span style="color: #339933;">:</span> <span style="color: #0000dd;">4</span><span style="color: #339933;">;</span>
  UCHAR  Adr <span style="color: #339933;">:</span> <span style="color: #0000dd;">4</span><span style="color: #339933;">;</span>
  UCHAR  TrackNumber<span style="color: #339933;">;</span>
  UCHAR  Reserved1<span style="color: #339933;">;</span>
  UCHAR  Address<span style="color: #009900;">&#91;</span><span style="color: #0000dd;">4</span><span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span> TRACK_DATA<span style="color: #339933;">;</span>
&nbsp;
<span style="color: #993333;">typedef</span> <span style="color: #993333;">struct</span> <span style="color: #009900;">&#123;</span>
  UCHAR  Length<span style="color: #009900;">&#91;</span><span style="color: #0000dd;">2</span><span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span>
  UCHAR  FirstTrack<span style="color: #339933;">;</span>
  UCHAR  LastTrack<span style="color: #339933;">;</span>
  TRACK_DATA  TrackData<span style="color: #009900;">&#91;</span><span style="color: #0000dd;">100</span><span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span> CDROM_TOC<span style="color: #339933;">;</span>
&nbsp;
<span style="color: #808080; font-style: italic;">/*
Funcion:
 lee_CDTOC
Parámetros:
 sDispositivo: ruta del dispositivo de CD.
 toc: estructura donde se almancena la tabla de contenidos del CD.
Descripción:
 Esta función se encarga de guardar en la variable toc la información de la tabla de contenidos del CD ubicado en el dispostivo lector de cdrom.
*/</span>
<span style="color: #993333;">void</span> lee_CDTOC<span style="color: #009900;">&#40;</span><span style="color: #993333;">char</span> <span style="color: #339933;">*</span>sLetra<span style="color: #339933;">,</span>CDROM_TOC <span style="color: #339933;">*</span>toc<span style="color: #009900;">&#41;</span>
<span style="color: #009900;">&#123;</span>
 HANDLE manejador<span style="color: #339933;">;</span>
 DWORD nTamBuffer<span style="color: #339933;">;</span>
 <span style="color: #993333;">char</span> sUnidad<span style="color: #009900;">&#91;</span><span style="color: #0000dd;">7</span><span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span>
&nbsp;
 sprintf<span style="color: #009900;">&#40;</span>sUnidad<span style="color: #339933;">,</span><span style="color: #ff0000;">&quot;\\\\.\\%s&quot;</span><span style="color: #339933;">,</span>sLetra<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
 manejador <span style="color: #339933;">=</span> CreateFile<span style="color: #009900;">&#40;</span>sUnidad<span style="color: #339933;">,</span> GENERIC_READ<span style="color: #339933;">,</span> FILE_SHARE_READ <span style="color: #339933;">|</span> FILE_SHARE_WRITE<span style="color: #339933;">,</span> NULL<span style="color: #339933;">,</span> OPEN_EXISTING<span style="color: #339933;">,</span> FILE_ATTRIBUTE_NORMAL<span style="color: #339933;">,</span> NULL<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
 <span style="color: #b1b100;">if</span><span style="color: #009900;">&#40;</span>manejador <span style="color: #339933;">==</span> INVALID_HANDLE_VALUE<span style="color: #009900;">&#41;</span>
 <span style="color: #009900;">&#123;</span>
  fprintf<span style="color: #009900;">&#40;</span>stderr<span style="color: #339933;">,</span><span style="color: #ff0000;">&quot;No se pudo acceder al disco de la unidad de CD<span style="color: #000099; font-weight: bold;">\n</span>&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
  <span style="color: #b1b100;">return</span><span style="color: #339933;">;</span>
 <span style="color: #009900;">&#125;</span>
&nbsp;
 <span style="color: #b1b100;">if</span> <span style="color: #009900;">&#40;</span>DeviceIoControl<span style="color: #009900;">&#40;</span>manejador<span style="color: #339933;">,</span> IOCTL_CDROM_READ_TOC<span style="color: #339933;">,</span> NULL<span style="color: #339933;">,</span> <span style="color: #0000dd;">0</span><span style="color: #339933;">,</span> toc<span style="color: #339933;">,</span> <span style="color: #993333;">sizeof</span><span style="color: #009900;">&#40;</span>CDROM_TOC<span style="color: #009900;">&#41;</span><span style="color: #339933;">,</span> <span style="color: #339933;">&amp;</span>nTamBuffer<span style="color: #339933;">,</span> NULL<span style="color: #009900;">&#41;</span> <span style="color: #339933;">==</span> FALSE<span style="color: #009900;">&#41;</span>
  fprintf<span style="color: #009900;">&#40;</span>stderr<span style="color: #339933;">,</span><span style="color: #ff0000;">&quot;No se pudo leer el contenido del CD<span style="color: #000099; font-weight: bold;">\n</span>&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
 CloseHandle<span style="color: #009900;">&#40;</span>manejador<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span>
&nbsp;
<span style="color: #808080; font-style: italic;">/*
Funcion:
 lee_InfoCDDB: Devuelve una cadena con los resultados de la petición.
Parámetros:
 sIDDisco: identificador único del cd.
 sBuffer: buffer donde almacenar los resultados de la petición.
Descripción:
 Esta función se encarga de pedir a freedb la información relacionada con un identificador de cd determinado y devolver todo el contenido de la petición.
*/</span>
<span style="color: #993333;">char</span> <span style="color: #339933;">*</span>lee_InfoCDDB<span style="color: #009900;">&#40;</span><span style="color: #993333;">char</span> <span style="color: #339933;">*</span>sIDDisco<span style="color: #339933;">,</span><span style="color: #993333;">char</span> <span style="color: #339933;">*</span>sBuffer<span style="color: #009900;">&#41;</span>
<span style="color: #009900;">&#123;</span>
 WSAData data<span style="color: #339933;">;</span>
 SOCKET sock<span style="color: #339933;">;</span>
 <span style="color: #993333;">struct</span> hostent <span style="color: #339933;">*</span>servidor<span style="color: #339933;">;</span>
 <span style="color: #993333;">struct</span> sockaddr_in destino<span style="color: #339933;">;</span>
 <span style="color: #993333;">char</span> sPeticion<span style="color: #009900;">&#91;</span><span style="color: #0000dd;">256</span><span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span>
 <span style="color: #993333;">int</span> nEnviados<span style="color: #339933;">,</span>nRecibidos<span style="color: #339933;">;</span>
&nbsp;
 <span style="color: #b1b100;">if</span><span style="color: #009900;">&#40;</span>WSAStartup<span style="color: #009900;">&#40;</span>MAKEWORD<span style="color: #009900;">&#40;</span> <span style="color: #0000dd;">2</span><span style="color: #339933;">,</span> <span style="color: #0000dd;">2</span> <span style="color: #009900;">&#41;</span><span style="color: #339933;">,&amp;</span>data<span style="color: #009900;">&#41;</span> <span style="color: #339933;">==</span> <span style="color: #0000dd;">0</span><span style="color: #009900;">&#41;</span>
 <span style="color: #009900;">&#123;</span>
  <span style="color: #b1b100;">if</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#40;</span>sock<span style="color: #339933;">=</span>socket<span style="color: #009900;">&#40;</span>PF_INET<span style="color: #339933;">,</span>SOCK_STREAM<span style="color: #339933;">,</span><span style="color: #0000dd;">0</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">==</span> INVALID_SOCKET<span style="color: #009900;">&#41;</span>
   fprintf<span style="color: #009900;">&#40;</span>stderr<span style="color: #339933;">,</span><span style="color: #ff0000;">&quot;No se pudo crear la conexion&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
  <span style="color: #b1b100;">else</span>
  <span style="color: #009900;">&#123;</span>
   <span style="color: #b1b100;">if</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#40;</span>servidor<span style="color: #339933;">=</span>gethostbyname<span style="color: #009900;">&#40;</span><span style="color: #ff0000;">&quot;freedb.freedb.org&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">==</span> NULL<span style="color: #009900;">&#41;</span>
    fprintf<span style="color: #009900;">&#40;</span>stderr<span style="color: #339933;">,</span><span style="color: #ff0000;">&quot;No se pudo obtener la IP del servidor&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
   <span style="color: #b1b100;">else</span>
   <span style="color: #009900;">&#123;</span>
    destino.<span style="color: #202020;">sin_family</span> <span style="color: #339933;">=</span> AF_INET<span style="color: #339933;">;</span>
    destino.<span style="color: #202020;">sin_port</span> <span style="color: #339933;">=</span> htons<span style="color: #009900;">&#40;</span><span style="color: #0000dd;">80</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    destino.<span style="color: #202020;">sin_addr</span> <span style="color: #339933;">=</span> <span style="color: #339933;">*</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#40;</span><span style="color: #993333;">struct</span> in_addr <span style="color: #339933;">*</span><span style="color: #009900;">&#41;</span>servidor<span style="color: #339933;">-&gt;</span>h_addr_list<span style="color: #009900;">&#91;</span><span style="color: #0000dd;">0</span><span style="color: #009900;">&#93;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    memset<span style="color: #009900;">&#40;</span><span style="color: #339933;">&amp;</span><span style="color: #009900;">&#40;</span>destino.<span style="color: #202020;">sin_zero</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">,</span> <span style="color: #ff0000;">''</span><span style="color: #339933;">,</span> <span style="color: #0000dd;">8</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #b1b100;">if</span><span style="color: #009900;">&#40;</span>connect<span style="color: #009900;">&#40;</span>sock<span style="color: #339933;">,</span> <span style="color: #009900;">&#40;</span><span style="color: #993333;">struct</span> sockaddr <span style="color: #339933;">*</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">&amp;</span>destino<span style="color: #339933;">,</span> <span style="color: #993333;">sizeof</span><span style="color: #009900;">&#40;</span><span style="color: #993333;">struct</span> sockaddr<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">==</span> SOCKET_ERROR<span style="color: #009900;">&#41;</span>
     fprintf<span style="color: #009900;">&#40;</span>stderr<span style="color: #339933;">,</span><span style="color: #ff0000;">&quot;No se pudo conectar al servidor&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #b1b100;">else</span>
    <span style="color: #009900;">&#123;</span>
     sprintf<span style="color: #009900;">&#40;</span>sPeticion<span style="color: #339933;">,</span><span style="color: #ff0000;">&quot;GET /~cddb/cddb.cgi?cmd=cddb+read+misc+%s&amp;hello=sistemasorp+sistemasorp.blogspot.com+testeoCDDB+1.0&amp;proto=1 HTTP/1.0<span style="color: #000099; font-weight: bold;">\r</span><span style="color: #000099; font-weight: bold;">\n</span>&quot;</span><span style="color: #339933;">,</span>sIDDisco<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
     strcat<span style="color: #009900;">&#40;</span>sPeticion<span style="color: #339933;">,</span><span style="color: #ff0000;">&quot;Host: freedb.freedb.org<span style="color: #000099; font-weight: bold;">\r</span><span style="color: #000099; font-weight: bold;">\n</span><span style="color: #000099; font-weight: bold;">\r</span><span style="color: #000099; font-weight: bold;">\n</span>&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
     nEnviados<span style="color: #339933;">=</span>send<span style="color: #009900;">&#40;</span>sock<span style="color: #339933;">,</span>sPeticion<span style="color: #339933;">,</span>strlen<span style="color: #009900;">&#40;</span>sPeticion<span style="color: #009900;">&#41;</span><span style="color: #339933;">,</span><span style="color: #0000dd;">0</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
     <span style="color: #b1b100;">if</span><span style="color: #009900;">&#40;</span>nEnviados <span style="color: #339933;">==</span> SOCKET_ERROR<span style="color: #009900;">&#41;</span>
      fprintf<span style="color: #009900;">&#40;</span>stderr<span style="color: #339933;">,</span><span style="color: #ff0000;">&quot;No se pudo enviar la peticion al servidor&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
     nRecibidos<span style="color: #339933;">=</span><span style="color: #0000dd;">0</span><span style="color: #339933;">;</span>
     <span style="color: #b1b100;">while</span><span style="color: #009900;">&#40;</span>strstr<span style="color: #009900;">&#40;</span>sBuffer<span style="color: #339933;">,</span><span style="color: #ff0000;">&quot;<span style="color: #000099; font-weight: bold;">\r</span><span style="color: #000099; font-weight: bold;">\n</span>.<span style="color: #000099; font-weight: bold;">\r</span><span style="color: #000099; font-weight: bold;">\n</span>&quot;</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">==</span> NULL<span style="color: #009900;">&#41;</span>
     <span style="color: #009900;">&#123;</span>
      nRecibidos<span style="color: #339933;">+=</span>recv<span style="color: #009900;">&#40;</span>sock<span style="color: #339933;">,</span>sBuffer<span style="color: #339933;">+</span>nRecibidos<span style="color: #339933;">,</span><span style="color: #0000dd;">1024</span><span style="color: #339933;">,</span><span style="color: #0000dd;">0</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
      sBuffer<span style="color: #009900;">&#91;</span>nRecibidos<span style="color: #009900;">&#93;</span><span style="color: #339933;">=</span><span style="color: #ff0000;">''</span><span style="color: #339933;">;</span>
     <span style="color: #009900;">&#125;</span>
&nbsp;
    <span style="color: #009900;">&#125;</span>
   <span style="color: #009900;">&#125;</span>
  <span style="color: #009900;">&#125;</span>
  WSACleanup<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
 <span style="color: #009900;">&#125;</span>
 <span style="color: #b1b100;">else</span>
  fprintf<span style="color: #009900;">&#40;</span>stderr<span style="color: #339933;">,</span><span style="color: #ff0000;">&quot;No se puedo inicializar la conexion&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
 <span style="color: #b1b100;">return</span> sBuffer<span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span>
&nbsp;
<span style="color: #808080; font-style: italic;">/*
Funcion:
 cddb_Suma: Devuelve un número sacado a través de una suma de cifras.
Parámetros:
 nDuracion: Duración en segundos de una pista.
Descripción:
 Esta función se encarga de sumar todas las cifras de distinto peso entre si para posteriormente devolver el resultado.
*/</span>
<span style="color: #993333;">int</span> cddb_Suma<span style="color: #009900;">&#40;</span><span style="color: #993333;">int</span> nDuracion<span style="color: #009900;">&#41;</span>
<span style="color: #009900;">&#123;</span>
 <span style="color: #993333;">int</span> nSuma <span style="color: #339933;">=</span> <span style="color: #0000dd;">0</span><span style="color: #339933;">;</span>
&nbsp;
 <span style="color: #b1b100;">while</span> <span style="color: #009900;">&#40;</span>nDuracion <span style="color: #339933;">&gt;</span> <span style="color: #0000dd;">0</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
  nSuma <span style="color: #339933;">=</span> nSuma <span style="color: #339933;">+</span> <span style="color: #009900;">&#40;</span>nDuracion <span style="color: #339933;">%</span> <span style="color: #0000dd;">10</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
  nDuracion <span style="color: #339933;">=</span> nDuracion <span style="color: #339933;">/</span> <span style="color: #0000dd;">10</span><span style="color: #339933;">;</span>
 <span style="color: #009900;">&#125;</span>
&nbsp;
 <span style="color: #b1b100;">return</span> nSuma<span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span>
&nbsp;
<span style="color: #808080; font-style: italic;">/*
Funcion:
 cddb_IDDisco: Devuelve en número que identifica al CD inequivocamente.
Parámetros:
 toc: Información de la tabla de contenidos del CD
Descripción:
 Esta función se encarga de calcular el identificador único de un CD a través de su tabla de contenidos
*/</span>
<span style="color: #993333;">unsigned</span> <span style="color: #993333;">long</span> cddb_IDDisco<span style="color: #009900;">&#40;</span>CDROM_TOC <span style="color: #339933;">*</span>toc<span style="color: #009900;">&#41;</span>
<span style="color: #009900;">&#123;</span>
 <span style="color: #993333;">int</span> nIndice<span style="color: #339933;">=</span><span style="color: #0000dd;">0</span><span style="color: #339933;">,</span>
  nTotalTiempo <span style="color: #339933;">=</span> <span style="color: #0000dd;">0</span><span style="color: #339933;">,</span>
  nSumatorio <span style="color: #339933;">=</span> <span style="color: #0000dd;">0</span><span style="color: #339933;">;</span>
 <span style="color: #993333;">int</span> nTotalPistas<span style="color: #339933;">;</span>
&nbsp;
 nTotalPistas<span style="color: #339933;">=</span>toc<span style="color: #339933;">-&gt;</span>LastTrack<span style="color: #339933;">-</span>toc<span style="color: #339933;">-&gt;</span>FirstTrack<span style="color: #339933;">+</span><span style="color: #0000dd;">1</span><span style="color: #339933;">;</span>
&nbsp;
 <span style="color: #b1b100;">while</span> <span style="color: #009900;">&#40;</span>nIndice <span style="color: #339933;">&lt;</span> nTotalPistas<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
  nSumatorio <span style="color: #339933;">=</span> nSumatorio <span style="color: #339933;">+</span> cddb_Suma<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#40;</span>toc<span style="color: #339933;">-&gt;</span>TrackData<span style="color: #009900;">&#91;</span>nIndice<span style="color: #009900;">&#93;</span>.<span style="color: #202020;">Address</span><span style="color: #009900;">&#91;</span><span style="color: #0000dd;">1</span><span style="color: #009900;">&#93;</span> <span style="color: #339933;">*</span> <span style="color: #0000dd;">60</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">+</span> toc<span style="color: #339933;">-&gt;</span>TrackData<span style="color: #009900;">&#91;</span>nIndice<span style="color: #009900;">&#93;</span>.<span style="color: #202020;">Address</span><span style="color: #009900;">&#91;</span><span style="color: #0000dd;">2</span><span style="color: #009900;">&#93;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
  nIndice<span style="color: #339933;">++;</span>
 <span style="color: #009900;">&#125;</span>
&nbsp;
 nTotalTiempo <span style="color: #339933;">=</span> <span style="color: #009900;">&#40;</span><span style="color: #009900;">&#40;</span>toc<span style="color: #339933;">-&gt;</span>TrackData<span style="color: #009900;">&#91;</span>toc<span style="color: #339933;">-&gt;</span>LastTrack<span style="color: #009900;">&#93;</span>.<span style="color: #202020;">Address</span><span style="color: #009900;">&#91;</span><span style="color: #0000dd;">1</span><span style="color: #009900;">&#93;</span> <span style="color: #339933;">*</span> <span style="color: #0000dd;">60</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">+</span> toc<span style="color: #339933;">-&gt;</span>TrackData<span style="color: #009900;">&#91;</span>toc<span style="color: #339933;">-&gt;</span>LastTrack<span style="color: #009900;">&#93;</span>.<span style="color: #202020;">Address</span><span style="color: #009900;">&#91;</span><span style="color: #0000dd;">2</span><span style="color: #009900;">&#93;</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">-</span>
     <span style="color: #009900;">&#40;</span><span style="color: #009900;">&#40;</span>toc<span style="color: #339933;">-&gt;</span>TrackData<span style="color: #009900;">&#91;</span><span style="color: #0000dd;">0</span><span style="color: #009900;">&#93;</span>.<span style="color: #202020;">Address</span><span style="color: #009900;">&#91;</span><span style="color: #0000dd;">1</span><span style="color: #009900;">&#93;</span> <span style="color: #339933;">*</span> <span style="color: #0000dd;">60</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">+</span> toc<span style="color: #339933;">-&gt;</span>TrackData<span style="color: #009900;">&#91;</span><span style="color: #0000dd;">0</span><span style="color: #009900;">&#93;</span>.<span style="color: #202020;">Address</span><span style="color: #009900;">&#91;</span><span style="color: #0000dd;">2</span><span style="color: #009900;">&#93;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
 <span style="color: #b1b100;">return</span> <span style="color: #009900;">&#40;</span><span style="color: #009900;">&#40;</span>nSumatorio <span style="color: #339933;">%</span> <span style="color: #208080;">0xff</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">&lt;&lt;</span> <span style="color: #0000dd;">24</span> <span style="color: #339933;">|</span> nTotalTiempo <span style="color: #339933;">&lt;&lt;</span> <span style="color: #0000dd;">8</span> <span style="color: #339933;">|</span> nTotalPistas<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span>
&nbsp;
<span style="color: #993333;">int</span> main<span style="color: #009900;">&#40;</span><span style="color: #993333;">int</span> argc<span style="color: #339933;">,</span> <span style="color: #993333;">char</span> <span style="color: #339933;">*</span>argv<span style="color: #009900;">&#91;</span> <span style="color: #009900;">&#93;</span><span style="color: #009900;">&#41;</span>
<span style="color: #009900;">&#123;</span>
 CDROM_TOC toc<span style="color: #339933;">;</span>
 <span style="color: #993333;">char</span> sIDDisco<span style="color: #009900;">&#91;</span><span style="color: #0000dd;">9</span><span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span>
 <span style="color: #993333;">char</span> <span style="color: #339933;">*</span>sBuffer<span style="color: #339933;">;</span>
&nbsp;
 <span style="color: #b1b100;">if</span><span style="color: #009900;">&#40;</span>argc<span style="color: #339933;">==</span><span style="color: #0000dd;">2</span><span style="color: #009900;">&#41;</span>
 <span style="color: #009900;">&#123;</span>
  memset<span style="color: #009900;">&#40;</span><span style="color: #339933;">&amp;</span>toc<span style="color: #339933;">,</span><span style="color: #0000dd;">0</span><span style="color: #339933;">,</span><span style="color: #993333;">sizeof</span><span style="color: #009900;">&#40;</span>CDROM_TOC<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
  lee_CDTOC<span style="color: #009900;">&#40;</span>argv<span style="color: #009900;">&#91;</span><span style="color: #0000dd;">1</span><span style="color: #009900;">&#93;</span><span style="color: #339933;">,&amp;</span>toc<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
  <span style="color: #b1b100;">if</span><span style="color: #009900;">&#40;</span>toc.<span style="color: #202020;">LastTrack</span><span style="color: #339933;">&gt;</span><span style="color: #0000dd;">0</span><span style="color: #009900;">&#41;</span>
  <span style="color: #009900;">&#123;</span>
   sprintf<span style="color: #009900;">&#40;</span>sIDDisco<span style="color: #339933;">,</span><span style="color: #ff0000;">&quot;%08x&quot;</span><span style="color: #339933;">,</span>cddb_IDDisco<span style="color: #009900;">&#40;</span><span style="color: #339933;">&amp;</span>toc<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
   <span style="color: #000066;">printf</span><span style="color: #009900;">&#40;</span><span style="color: #ff0000;">&quot;El ID del disco es %s<span style="color: #000099; font-weight: bold;">\n</span>&quot;</span><span style="color: #339933;">,</span>sIDDisco<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
   sBuffer<span style="color: #339933;">=</span><span style="color: #009900;">&#40;</span><span style="color: #993333;">char</span> <span style="color: #339933;">*</span><span style="color: #009900;">&#41;</span>malloc<span style="color: #009900;">&#40;</span><span style="color: #0000dd;">4096</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
   <span style="color: #b1b100;">if</span><span style="color: #009900;">&#40;</span>sBuffer <span style="color: #339933;">==</span> NULL<span style="color: #009900;">&#41;</span>
   <span style="color: #009900;">&#123;</span>
    fprintf<span style="color: #009900;">&#40;</span>stderr<span style="color: #339933;">,</span><span style="color: #ff0000;">&quot;No se pudo alojar memoria&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #b1b100;">return</span> <span style="color: #0000dd;">1</span><span style="color: #339933;">;</span>
   <span style="color: #009900;">&#125;</span>   
   <span style="color: #339933;">*</span>sBuffer<span style="color: #339933;">=</span><span style="color: #ff0000;">''</span><span style="color: #339933;">;</span>
   lee_InfoCDDB<span style="color: #009900;">&#40;</span>sIDDisco<span style="color: #339933;">,</span>sBuffer<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
   <span style="color: #b1b100;">if</span><span style="color: #009900;">&#40;</span><span style="color: #339933;">*</span>sBuffer<span style="color: #339933;">==</span><span style="color: #ff0000;">''</span><span style="color: #009900;">&#41;</span>
    <span style="color: #b1b100;">return</span> <span style="color: #0000dd;">1</span><span style="color: #339933;">;</span>
   <span style="color: #000066;">printf</span><span style="color: #009900;">&#40;</span><span style="color: #ff0000;">&quot;La información del disco es:<span style="color: #000099; font-weight: bold;">\n</span>%s&quot;</span><span style="color: #339933;">,</span>sBuffer<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
   free<span style="color: #009900;">&#40;</span>sBuffer<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
  <span style="color: #009900;">&#125;</span>
  <span style="color: #b1b100;">else</span>
   <span style="color: #b1b100;">return</span> <span style="color: #0000dd;">1</span><span style="color: #339933;">;</span>
 <span style="color: #009900;">&#125;</span>
 <span style="color: #b1b100;">else</span>
 <span style="color: #009900;">&#123;</span>
  fprintf<span style="color: #009900;">&#40;</span>stderr<span style="color: #339933;">,</span><span style="color: #ff0000;">&quot;La sintaxis es: %s &lt;unidad de cd&gt;<span style="color: #000099; font-weight: bold;">\n</span>Ejemplo: %s d:<span style="color: #000099; font-weight: bold;">\n</span>&quot;</span><span style="color: #339933;">,</span>argv<span style="color: #009900;">&#91;</span><span style="color: #0000dd;">0</span><span style="color: #009900;">&#93;</span><span style="color: #339933;">,</span>argv<span style="color: #009900;">&#91;</span><span style="color: #0000dd;">0</span><span style="color: #009900;">&#93;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
  <span style="color: #b1b100;">return</span> <span style="color: #0000dd;">1</span><span style="color: #339933;">;</span>
 <span style="color: #009900;">&#125;</span>
&nbsp;
 <span style="color: #b1b100;">return</span> <span style="color: #0000dd;">0</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p><strong>LINUX</strong>(<a href="http://www.quejateportodo.com/blog/toc.tar.gz">ejecutable y fuentes</a>)</p>

<div class="wp_syntax"><div class="code"><pre class="c" style="font-family:monospace;"><span style="color: #339933;">#include &lt;stdio.h&gt;</span>
<span style="color: #339933;">#include &lt;stdlib.h&gt;</span>
<span style="color: #339933;">#include &lt;fcntl.h&gt;</span>
<span style="color: #339933;">#include &lt;stdarg.h&gt;</span>
<span style="color: #339933;">#include &lt;errno.h&gt;</span>
<span style="color: #339933;">#include &lt;netdb.h&gt;</span>
<span style="color: #339933;">#include &lt;unistd.h&gt;</span>
<span style="color: #339933;">#include &lt;string.h&gt;</span>
<span style="color: #339933;">#include &lt;sys/ioctl.h&gt;</span>
<span style="color: #339933;">#include &lt;sys/types.h&gt;</span>
<span style="color: #339933;">#include &lt;sys/socket.h&gt;</span>
&nbsp;
<span style="color: #339933;">#if defined linux</span>
<span style="color: #339933;">#include &lt;linux/cdrom.h&gt;</span>
<span style="color: #339933;">#elif defined sun</span>
<span style="color: #339933;">#include &lt;sys/cdio.h&gt;</span>
<span style="color: #339933;">#endif</span>
&nbsp;
<span style="color: #993333;">typedef</span> <span style="color: #993333;">struct</span> <span style="color: #009900;">&#123;</span>
 <span style="color: #993333;">int</span> minutos<span style="color: #339933;">,</span> segundos<span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span> TRACK_DATA<span style="color: #339933;">;</span>
&nbsp;
<span style="color: #993333;">typedef</span> <span style="color: #993333;">struct</span> <span style="color: #009900;">&#123;</span>
  <span style="color: #993333;">unsigned</span> <span style="color: #993333;">char</span>  FirstTrack<span style="color: #339933;">;</span>
  <span style="color: #993333;">unsigned</span> <span style="color: #993333;">char</span> LastTrack<span style="color: #339933;">;</span> 
  TRACK_DATA  TrackData<span style="color: #009900;">&#91;</span><span style="color: #0000dd;">100</span><span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span> CDROM_TOC<span style="color: #339933;">;</span>
&nbsp;
<span style="color: #808080; font-style: italic;">/*
Funcion:
 lee_CDTOC
Parámetros:
 sDispositivo: ruta del dispositivo de CD.
 toc: estructura donde se almancena la tabla de contenidos del CD.
Descripción:
 Esta función se encarga de guardar en la variable toc la información de la tabla de contenidos del CD ubicado en el dispostivo lector de cdrom.
*/</span>
<span style="color: #993333;">void</span> lee_CDTOC<span style="color: #009900;">&#40;</span><span style="color: #993333;">char</span> <span style="color: #339933;">*</span>sDispositivo<span style="color: #339933;">,</span>CDROM_TOC <span style="color: #339933;">*</span>toc<span style="color: #009900;">&#41;</span>
<span style="color: #009900;">&#123;</span>
 <span style="color: #993333;">struct</span> cdrom_tochdr tochdr<span style="color: #339933;">;</span>
 <span style="color: #993333;">struct</span> cdrom_tocentry tocentry<span style="color: #339933;">;</span>
 <span style="color: #993333;">int</span> nIndice<span style="color: #339933;">,</span> manejador<span style="color: #339933;">;</span>
&nbsp;
 manejador<span style="color: #339933;">=</span> open<span style="color: #009900;">&#40;</span>sDispositivo<span style="color: #339933;">,</span> O_RDONLY <span style="color: #339933;">|</span> O_NONBLOCK<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
 <span style="color: #b1b100;">if</span><span style="color: #009900;">&#40;</span>manejador <span style="color: #339933;">==</span> <span style="color: #339933;">-</span><span style="color: #0000dd;">1</span><span style="color: #009900;">&#41;</span>
 <span style="color: #009900;">&#123;</span>
  fprintf<span style="color: #009900;">&#40;</span>stderr<span style="color: #339933;">,</span><span style="color: #ff0000;">&quot;No se pudo acceder al disco de la unidad de CD<span style="color: #000099; font-weight: bold;">\n</span>&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
  <span style="color: #b1b100;">return</span><span style="color: #339933;">;</span>
 <span style="color: #009900;">&#125;</span>
&nbsp;
 <span style="color: #b1b100;">if</span> <span style="color: #009900;">&#40;</span>ioctl<span style="color: #009900;">&#40;</span>manejador<span style="color: #339933;">,</span> CDROMREADTOCHDR<span style="color: #339933;">,</span> <span style="color: #339933;">&amp;</span>tochdr<span style="color: #009900;">&#41;</span> <span style="color: #339933;">==</span> <span style="color: #339933;">-</span><span style="color: #0000dd;">1</span><span style="color: #009900;">&#41;</span>
  fprintf<span style="color: #009900;">&#40;</span>stderr<span style="color: #339933;">,</span><span style="color: #ff0000;">&quot;No se pudo leer el contenido del CD<span style="color: #000099; font-weight: bold;">\n</span>&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
 <span style="color: #b1b100;">else</span>
 <span style="color: #009900;">&#123;</span>
  toc<span style="color: #339933;">-&gt;</span>FirstTrack<span style="color: #339933;">=</span>tochdr.<span style="color: #202020;">cdth_trk0</span><span style="color: #339933;">;</span>
  toc<span style="color: #339933;">-&gt;</span>LastTrack<span style="color: #339933;">=</span>tochdr.<span style="color: #202020;">cdth_trk1</span><span style="color: #339933;">;</span>
  <span style="color: #b1b100;">for</span> <span style="color: #009900;">&#40;</span>nIndice <span style="color: #339933;">=</span> toc<span style="color: #339933;">-&gt;</span>FirstTrack<span style="color: #339933;">;</span> nIndice <span style="color: #339933;">&lt;=</span> toc<span style="color: #339933;">-&gt;</span>LastTrack<span style="color: #339933;">;</span> nIndice<span style="color: #339933;">++</span><span style="color: #009900;">&#41;</span> 
  <span style="color: #009900;">&#123;</span>
   tocentry.<span style="color: #202020;">cdte_track</span> <span style="color: #339933;">=</span> nIndice<span style="color: #339933;">;</span>
   tocentry.<span style="color: #202020;">cdte_format</span> <span style="color: #339933;">=</span> CDROM_MSF<span style="color: #339933;">;</span>
   ioctl<span style="color: #009900;">&#40;</span>manejador<span style="color: #339933;">,</span> CDROMREADTOCENTRY<span style="color: #339933;">,</span> <span style="color: #339933;">&amp;</span>tocentry<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
   toc<span style="color: #339933;">-&gt;</span>TrackData<span style="color: #009900;">&#91;</span>nIndice<span style="color: #339933;">-</span><span style="color: #0000dd;">1</span><span style="color: #009900;">&#93;</span>.<span style="color: #202020;">minutos</span> <span style="color: #339933;">=</span> tocentry.<span style="color: #202020;">cdte_addr</span>.<span style="color: #202020;">msf</span>.<span style="color: #202020;">minute</span><span style="color: #339933;">;</span>
   toc<span style="color: #339933;">-&gt;</span>TrackData<span style="color: #009900;">&#91;</span>nIndice<span style="color: #339933;">-</span><span style="color: #0000dd;">1</span><span style="color: #009900;">&#93;</span>.<span style="color: #202020;">segundos</span> <span style="color: #339933;">=</span> tocentry.<span style="color: #202020;">cdte_addr</span>.<span style="color: #202020;">msf</span>.<span style="color: #202020;">second</span><span style="color: #339933;">;</span>
  <span style="color: #009900;">&#125;</span>
  tocentry.<span style="color: #202020;">cdte_track</span> <span style="color: #339933;">=</span> <span style="color: #208080;">0xAA</span><span style="color: #339933;">;</span>
  tocentry.<span style="color: #202020;">cdte_format</span> <span style="color: #339933;">=</span> CDROM_MSF<span style="color: #339933;">;</span>
  ioctl<span style="color: #009900;">&#40;</span>manejador<span style="color: #339933;">,</span> CDROMREADTOCENTRY<span style="color: #339933;">,</span> <span style="color: #339933;">&amp;</span>tocentry<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
  toc<span style="color: #339933;">-&gt;</span>TrackData<span style="color: #009900;">&#91;</span>toc<span style="color: #339933;">-&gt;</span>LastTrack<span style="color: #009900;">&#93;</span>.<span style="color: #202020;">minutos</span> <span style="color: #339933;">=</span> tocentry.<span style="color: #202020;">cdte_addr</span>.<span style="color: #202020;">msf</span>.<span style="color: #202020;">minute</span><span style="color: #339933;">;</span>
  toc<span style="color: #339933;">-&gt;</span>TrackData<span style="color: #009900;">&#91;</span>toc<span style="color: #339933;">-&gt;</span>LastTrack<span style="color: #009900;">&#93;</span>.<span style="color: #202020;">segundos</span> <span style="color: #339933;">=</span> tocentry.<span style="color: #202020;">cdte_addr</span>.<span style="color: #202020;">msf</span>.<span style="color: #202020;">second</span><span style="color: #339933;">;</span>
 <span style="color: #009900;">&#125;</span>
 close<span style="color: #009900;">&#40;</span>manejador<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span>
&nbsp;
<span style="color: #808080; font-style: italic;">/*
Funcion:
 lee_InfoCDDB: Devuelve una cadena con los resultados de la petición.
Parámetros:
 sIDDisco: identificador único del cd.
 sBuffer: buffer donde almacenar los resultados de la petición.
Descripción:
 Esta función se encarga de pedir a freedb la información relacionada con un identificador de cd determinado y devolver todo el contenido de la petición.
*/</span>
<span style="color: #993333;">char</span> <span style="color: #339933;">*</span>lee_InfoCDDB<span style="color: #009900;">&#40;</span><span style="color: #993333;">char</span> <span style="color: #339933;">*</span>sIDDisco<span style="color: #339933;">,</span><span style="color: #993333;">char</span> <span style="color: #339933;">*</span>sBuffer<span style="color: #009900;">&#41;</span>
<span style="color: #009900;">&#123;</span>
 <span style="color: #993333;">int</span> sock<span style="color: #339933;">;</span>
 <span style="color: #993333;">struct</span> hostent <span style="color: #339933;">*</span>servidor<span style="color: #339933;">;</span>
 <span style="color: #993333;">struct</span> sockaddr_in destino<span style="color: #339933;">;</span>
 <span style="color: #993333;">char</span> sPeticion<span style="color: #009900;">&#91;</span><span style="color: #0000dd;">256</span><span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span>
 <span style="color: #993333;">int</span> nEnviados<span style="color: #339933;">,</span>nRecibidos<span style="color: #339933;">;</span>
&nbsp;
 <span style="color: #b1b100;">if</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#40;</span>sock<span style="color: #339933;">=</span>socket<span style="color: #009900;">&#40;</span>PF_INET<span style="color: #339933;">,</span>SOCK_STREAM<span style="color: #339933;">,</span><span style="color: #0000dd;">0</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">==</span> <span style="color: #339933;">-</span><span style="color: #0000dd;">1</span><span style="color: #009900;">&#41;</span>
  fprintf<span style="color: #009900;">&#40;</span>stderr<span style="color: #339933;">,</span><span style="color: #ff0000;">&quot;No se pudo crear la conexion&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
 <span style="color: #b1b100;">else</span>
 <span style="color: #009900;">&#123;</span>
  <span style="color: #b1b100;">if</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#40;</span>servidor<span style="color: #339933;">=</span>gethostbyname<span style="color: #009900;">&#40;</span><span style="color: #ff0000;">&quot;freedb.freedb.org&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">==</span>NULL<span style="color: #009900;">&#41;</span>
   fprintf<span style="color: #009900;">&#40;</span>stderr<span style="color: #339933;">,</span><span style="color: #ff0000;">&quot;No se pudo obtener la IP del servidor&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
  <span style="color: #b1b100;">else</span>
  <span style="color: #009900;">&#123;</span>
   destino.<span style="color: #202020;">sin_family</span> <span style="color: #339933;">=</span> AF_INET<span style="color: #339933;">;</span>
   destino.<span style="color: #202020;">sin_port</span> <span style="color: #339933;">=</span> htons<span style="color: #009900;">&#40;</span><span style="color: #0000dd;">80</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
   destino.<span style="color: #202020;">sin_addr</span> <span style="color: #339933;">=</span> <span style="color: #339933;">*</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#40;</span><span style="color: #993333;">struct</span> in_addr <span style="color: #339933;">*</span><span style="color: #009900;">&#41;</span>servidor<span style="color: #339933;">-&gt;</span>h_addr_list<span style="color: #009900;">&#91;</span><span style="color: #0000dd;">0</span><span style="color: #009900;">&#93;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
   memset<span style="color: #009900;">&#40;</span><span style="color: #339933;">&amp;</span><span style="color: #009900;">&#40;</span>destino.<span style="color: #202020;">sin_zero</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">,</span> <span style="color: #ff0000;">''</span><span style="color: #339933;">,</span> <span style="color: #0000dd;">8</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
   <span style="color: #b1b100;">if</span><span style="color: #009900;">&#40;</span>connect<span style="color: #009900;">&#40;</span>sock<span style="color: #339933;">,</span> <span style="color: #009900;">&#40;</span><span style="color: #993333;">struct</span> sockaddr <span style="color: #339933;">*</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">&amp;</span>destino<span style="color: #339933;">,</span> <span style="color: #993333;">sizeof</span><span style="color: #009900;">&#40;</span><span style="color: #993333;">struct</span> sockaddr<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">==</span> <span style="color: #339933;">-</span><span style="color: #0000dd;">1</span><span style="color: #009900;">&#41;</span>
    fprintf<span style="color: #009900;">&#40;</span>stderr<span style="color: #339933;">,</span><span style="color: #ff0000;">&quot;No se pudo conectar al servidor&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
   <span style="color: #b1b100;">else</span>
   <span style="color: #009900;">&#123;</span>
    sprintf<span style="color: #009900;">&#40;</span>sPeticion<span style="color: #339933;">,</span><span style="color: #ff0000;">&quot;GET /~cddb/cddb.cgi?cmd=cddb+read+misc+%s&amp;hello=sistemasorp+sistemasorp.blogspot.com+testeoCDDB+1.0&amp;proto=1 HTTP/1.0<span style="color: #000099; font-weight: bold;">\r</span><span style="color: #000099; font-weight: bold;">\n</span>&quot;</span><span style="color: #339933;">,</span>sIDDisco<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    strcat<span style="color: #009900;">&#40;</span>sPeticion<span style="color: #339933;">,</span><span style="color: #ff0000;">&quot;Host: freedb.freedb.org<span style="color: #000099; font-weight: bold;">\r</span><span style="color: #000099; font-weight: bold;">\n</span><span style="color: #000099; font-weight: bold;">\r</span><span style="color: #000099; font-weight: bold;">\n</span>&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    nEnviados<span style="color: #339933;">=</span>send<span style="color: #009900;">&#40;</span>sock<span style="color: #339933;">,</span>sPeticion<span style="color: #339933;">,</span>strlen<span style="color: #009900;">&#40;</span>sPeticion<span style="color: #009900;">&#41;</span><span style="color: #339933;">,</span><span style="color: #0000dd;">0</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #b1b100;">if</span><span style="color: #009900;">&#40;</span>nEnviados <span style="color: #339933;">==</span> <span style="color: #339933;">-</span><span style="color: #0000dd;">1</span><span style="color: #009900;">&#41;</span>
     fprintf<span style="color: #009900;">&#40;</span>stderr<span style="color: #339933;">,</span><span style="color: #ff0000;">&quot;No se pudo enviar la peticion al servidor&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    nRecibidos<span style="color: #339933;">=</span><span style="color: #0000dd;">0</span><span style="color: #339933;">;</span>
    <span style="color: #b1b100;">while</span><span style="color: #009900;">&#40;</span>strstr<span style="color: #009900;">&#40;</span>sBuffer<span style="color: #339933;">,</span><span style="color: #ff0000;">&quot;<span style="color: #000099; font-weight: bold;">\r</span><span style="color: #000099; font-weight: bold;">\n</span>.<span style="color: #000099; font-weight: bold;">\r</span><span style="color: #000099; font-weight: bold;">\n</span>&quot;</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">==</span> NULL<span style="color: #009900;">&#41;</span>
    <span style="color: #009900;">&#123;</span>
     nRecibidos<span style="color: #339933;">+=</span>recv<span style="color: #009900;">&#40;</span>sock<span style="color: #339933;">,</span>sBuffer<span style="color: #339933;">+</span>nRecibidos<span style="color: #339933;">,</span><span style="color: #0000dd;">1024</span><span style="color: #339933;">,</span><span style="color: #0000dd;">0</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
     sBuffer<span style="color: #009900;">&#91;</span>nRecibidos<span style="color: #009900;">&#93;</span><span style="color: #339933;">=</span><span style="color: #ff0000;">''</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
&nbsp;
   <span style="color: #009900;">&#125;</span>
  <span style="color: #009900;">&#125;</span>
 <span style="color: #009900;">&#125;</span>
 <span style="color: #b1b100;">return</span> sBuffer<span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span>
&nbsp;
<span style="color: #808080; font-style: italic;">/*
Funcion:
 cddb_Suma: Devuelve un número sacado a través de una suma de cifras.
Parámetros:
 nDuracion: Duración en segundos de una pista.
Descripción:
 Esta función se encarga de sumar todas las cifras de distinto peso entre si para posteriormente devolver el resultado.
*/</span>
<span style="color: #993333;">int</span> cddb_Suma<span style="color: #009900;">&#40;</span><span style="color: #993333;">int</span> nDuracion<span style="color: #009900;">&#41;</span>
<span style="color: #009900;">&#123;</span>
 <span style="color: #993333;">int</span> nSuma <span style="color: #339933;">=</span> <span style="color: #0000dd;">0</span><span style="color: #339933;">;</span>
&nbsp;
 <span style="color: #b1b100;">while</span> <span style="color: #009900;">&#40;</span>nDuracion <span style="color: #339933;">&gt;</span> <span style="color: #0000dd;">0</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
  nSuma <span style="color: #339933;">=</span> nSuma <span style="color: #339933;">+</span> <span style="color: #009900;">&#40;</span>nDuracion <span style="color: #339933;">%</span> <span style="color: #0000dd;">10</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
  nDuracion <span style="color: #339933;">=</span> nDuracion <span style="color: #339933;">/</span> <span style="color: #0000dd;">10</span><span style="color: #339933;">;</span>
 <span style="color: #009900;">&#125;</span>
&nbsp;
 <span style="color: #b1b100;">return</span> nSuma<span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span>
&nbsp;
<span style="color: #808080; font-style: italic;">/*
Funcion:
 cddb_IDDisco: Devuelve en número que identifica al CD inequivocamente.
Parámetros:
 toc: Información de la tabla de contenidos del CD
Descripción:
 Esta función se encarga de calcular el identificador único de un CD a través de su tabla de contenidos
*/</span>
<span style="color: #993333;">unsigned</span> <span style="color: #993333;">long</span> cddb_IDDisco<span style="color: #009900;">&#40;</span>CDROM_TOC <span style="color: #339933;">*</span>toc<span style="color: #009900;">&#41;</span>
<span style="color: #009900;">&#123;</span>
 <span style="color: #993333;">int</span> nIndice<span style="color: #339933;">=</span><span style="color: #0000dd;">0</span><span style="color: #339933;">,</span>
  nTotalTiempo <span style="color: #339933;">=</span> <span style="color: #0000dd;">0</span><span style="color: #339933;">,</span>
  nSumatorio <span style="color: #339933;">=</span> <span style="color: #0000dd;">0</span><span style="color: #339933;">;</span>
 <span style="color: #993333;">int</span> nTotalPistas<span style="color: #339933;">;</span>
&nbsp;
 nTotalPistas<span style="color: #339933;">=</span>toc<span style="color: #339933;">-&gt;</span>LastTrack<span style="color: #339933;">-</span>toc<span style="color: #339933;">-&gt;</span>FirstTrack<span style="color: #339933;">+</span><span style="color: #0000dd;">1</span><span style="color: #339933;">;</span>
&nbsp;
 <span style="color: #b1b100;">while</span> <span style="color: #009900;">&#40;</span>nIndice <span style="color: #339933;">&lt;</span> nTotalPistas<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
  nSumatorio <span style="color: #339933;">=</span> nSumatorio <span style="color: #339933;">+</span> cddb_Suma<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#40;</span>toc<span style="color: #339933;">-&gt;</span>TrackData<span style="color: #009900;">&#91;</span>nIndice<span style="color: #009900;">&#93;</span>.<span style="color: #202020;">minutos</span> <span style="color: #339933;">*</span> <span style="color: #0000dd;">60</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">+</span> toc<span style="color: #339933;">-&gt;</span>TrackData<span style="color: #009900;">&#91;</span>nIndice<span style="color: #009900;">&#93;</span>.<span style="color: #202020;">segundos</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
  nIndice<span style="color: #339933;">++;</span>
 <span style="color: #009900;">&#125;</span>
&nbsp;
 nTotalTiempo <span style="color: #339933;">=</span> <span style="color: #009900;">&#40;</span><span style="color: #009900;">&#40;</span>toc<span style="color: #339933;">-&gt;</span>TrackData<span style="color: #009900;">&#91;</span>toc<span style="color: #339933;">-&gt;</span>LastTrack<span style="color: #009900;">&#93;</span>.<span style="color: #202020;">minutos</span><span style="color: #339933;">*</span> <span style="color: #0000dd;">60</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">+</span> toc<span style="color: #339933;">-&gt;</span>TrackData<span style="color: #009900;">&#91;</span>toc<span style="color: #339933;">-&gt;</span>LastTrack<span style="color: #009900;">&#93;</span>.<span style="color: #202020;">segundos</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">-</span>
     <span style="color: #009900;">&#40;</span><span style="color: #009900;">&#40;</span>toc<span style="color: #339933;">-&gt;</span>TrackData<span style="color: #009900;">&#91;</span><span style="color: #0000dd;">0</span><span style="color: #009900;">&#93;</span>.<span style="color: #202020;">minutos</span> <span style="color: #339933;">*</span> <span style="color: #0000dd;">60</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">+</span> toc<span style="color: #339933;">-&gt;</span>TrackData<span style="color: #009900;">&#91;</span><span style="color: #0000dd;">0</span><span style="color: #009900;">&#93;</span>.<span style="color: #202020;">segundos</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
 <span style="color: #b1b100;">return</span> <span style="color: #009900;">&#40;</span><span style="color: #009900;">&#40;</span>nSumatorio <span style="color: #339933;">%</span> <span style="color: #208080;">0xff</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">&lt;&lt;</span> <span style="color: #0000dd;">24</span> <span style="color: #339933;">|</span> nTotalTiempo <span style="color: #339933;">&lt;&lt;</span> <span style="color: #0000dd;">8</span> <span style="color: #339933;">|</span> nTotalPistas<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span>
&nbsp;
<span style="color: #993333;">int</span> main<span style="color: #009900;">&#40;</span><span style="color: #993333;">int</span> argc<span style="color: #339933;">,</span> <span style="color: #993333;">char</span> <span style="color: #339933;">*</span>argv<span style="color: #009900;">&#91;</span> <span style="color: #009900;">&#93;</span><span style="color: #009900;">&#41;</span>
<span style="color: #009900;">&#123;</span>
 CDROM_TOC toc<span style="color: #339933;">;</span>
 <span style="color: #993333;">char</span> sIDDisco<span style="color: #009900;">&#91;</span><span style="color: #0000dd;">9</span><span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span>
 <span style="color: #993333;">char</span> <span style="color: #339933;">*</span>sBuffer<span style="color: #339933;">;</span>
&nbsp;
 <span style="color: #b1b100;">if</span><span style="color: #009900;">&#40;</span>argc<span style="color: #339933;">==</span><span style="color: #0000dd;">2</span><span style="color: #009900;">&#41;</span>
 <span style="color: #009900;">&#123;</span>
  memset<span style="color: #009900;">&#40;</span><span style="color: #339933;">&amp;</span>toc<span style="color: #339933;">,</span><span style="color: #0000dd;">0</span><span style="color: #339933;">,</span><span style="color: #993333;">sizeof</span><span style="color: #009900;">&#40;</span>CDROM_TOC<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
  lee_CDTOC<span style="color: #009900;">&#40;</span>argv<span style="color: #009900;">&#91;</span><span style="color: #0000dd;">1</span><span style="color: #009900;">&#93;</span><span style="color: #339933;">,&amp;</span>toc<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
  <span style="color: #b1b100;">if</span><span style="color: #009900;">&#40;</span>toc.<span style="color: #202020;">LastTrack</span><span style="color: #339933;">&gt;</span><span style="color: #0000dd;">0</span><span style="color: #009900;">&#41;</span>
  <span style="color: #009900;">&#123;</span>
   sprintf<span style="color: #009900;">&#40;</span>sIDDisco<span style="color: #339933;">,</span><span style="color: #ff0000;">&quot;%08x&quot;</span><span style="color: #339933;">,</span>cddb_IDDisco<span style="color: #009900;">&#40;</span><span style="color: #339933;">&amp;</span>toc<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
   <span style="color: #000066;">printf</span><span style="color: #009900;">&#40;</span><span style="color: #ff0000;">&quot;El ID del disco es %s<span style="color: #000099; font-weight: bold;">\n</span>&quot;</span><span style="color: #339933;">,</span>sIDDisco<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
   sBuffer<span style="color: #339933;">=</span><span style="color: #009900;">&#40;</span><span style="color: #993333;">char</span> <span style="color: #339933;">*</span><span style="color: #009900;">&#41;</span>malloc<span style="color: #009900;">&#40;</span><span style="color: #0000dd;">4096</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
   <span style="color: #b1b100;">if</span><span style="color: #009900;">&#40;</span>sBuffer <span style="color: #339933;">==</span> NULL<span style="color: #009900;">&#41;</span>
   <span style="color: #009900;">&#123;</span>
    fprintf<span style="color: #009900;">&#40;</span>stderr<span style="color: #339933;">,</span><span style="color: #ff0000;">&quot;No se pudo alojar memoria&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #b1b100;">return</span> <span style="color: #0000dd;">1</span><span style="color: #339933;">;</span>
   <span style="color: #009900;">&#125;</span>
   <span style="color: #339933;">*</span>sBuffer<span style="color: #339933;">=</span><span style="color: #ff0000;">''</span><span style="color: #339933;">;</span>
   lee_InfoCDDB<span style="color: #009900;">&#40;</span>sIDDisco<span style="color: #339933;">,</span>sBuffer<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
   <span style="color: #b1b100;">if</span><span style="color: #009900;">&#40;</span><span style="color: #339933;">*</span>sBuffer<span style="color: #339933;">==</span><span style="color: #ff0000;">''</span><span style="color: #009900;">&#41;</span>
    <span style="color: #b1b100;">return</span> <span style="color: #0000dd;">1</span><span style="color: #339933;">;</span>
   <span style="color: #000066;">printf</span><span style="color: #009900;">&#40;</span><span style="color: #ff0000;">&quot;La información del disco es:<span style="color: #000099; font-weight: bold;">\n</span>%s&quot;</span><span style="color: #339933;">,</span>sBuffer<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
   free<span style="color: #009900;">&#40;</span>sBuffer<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
  <span style="color: #009900;">&#125;</span>
  <span style="color: #b1b100;">else</span>
   <span style="color: #b1b100;">return</span> <span style="color: #0000dd;">1</span><span style="color: #339933;">;</span>
 <span style="color: #009900;">&#125;</span>
 <span style="color: #b1b100;">else</span>
 <span style="color: #009900;">&#123;</span>
  fprintf<span style="color: #009900;">&#40;</span>stderr<span style="color: #339933;">,</span><span style="color: #ff0000;">&quot;La sintaxis es: %s &lt;dispositivo de cd&gt;<span style="color: #000099; font-weight: bold;">\n</span>Ejemplo: %s /dev/cdrom<span style="color: #000099; font-weight: bold;">\n</span>&quot;</span><span style="color: #339933;">,</span>argv<span style="color: #009900;">&#91;</span><span style="color: #0000dd;">0</span><span style="color: #009900;">&#93;</span><span style="color: #339933;">,</span>argv<span style="color: #009900;">&#91;</span><span style="color: #0000dd;">0</span><span style="color: #009900;">&#93;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
  <span style="color: #b1b100;">return</span> <span style="color: #0000dd;">1</span><span style="color: #339933;">;</span>
 <span style="color: #009900;">&#125;</span>
&nbsp;
 <span style="color: #b1b100;">return</span> <span style="color: #0000dd;">0</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

]]></content:encoded>
			<wfw:commentRss>http://www.sistemasorp.es/2005/11/06/recuperar-los-titulos-de-las-canciones-de-un-cd-con-freedb/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>webchat en tiempo real con php y mysql</title>
		<link>http://www.sistemasorp.es/2005/11/01/webchat-en-tiempo-real-con-php-y-mysql/</link>
		<comments>http://www.sistemasorp.es/2005/11/01/webchat-en-tiempo-real-con-php-y-mysql/#comments</comments>
		<pubDate>Tue, 01 Nov 2005 14:23:00 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://www.sistemasorp.es/2005/11/01/webchat-en-tiempo-real-con-php-y-mysql/</guid>
		<description><![CDATA[Después de un pequeño descanso volvemos a las andadas. Esta vez voy a mostrar como crear un webchat en tiempo real. El problema de los webchat es que la inmensa mayoría de los que existen se dedican a refrescar la página de la charla cada X tiempo o cuando el usuario ha escrito un mensaje. [...]]]></description>
			<content:encoded><![CDATA[<p>Después de un pequeño descanso volvemos a las andadas. Esta vez voy a mostrar como crear un webchat en tiempo real.</p>
<p>El problema de los webchat es que la inmensa mayoría de los que existen se dedican a refrescar la página de la charla cada X tiempo o cuando el usuario ha escrito un mensaje. Esto es debido a que el protocolo HTTP esta diseñado para que una vez recibido los datos cierre la conexión, y si queremos recuperar datos nuevos tenemos que hacer una nueva petición.</p>
<p>Para lograr una interactividad y un realismo temporal cercanos al irc, messenger, etc. y seguir usando la web tenemos que usar un truco, y es crear una página que nunca termine de ejecutarse. Quizá os pregunteis que si nunca termina de ejecutarse, entónces no saldrá ningún resultado, pues bién, podemos desactivar el buffer del php desde el principio o hacer un volcado continuo para que cada dato nuevo se vaya enviando al navegador del cliente. Los navegadores muestran el contenido según les va llegando, por lo que una sentencia como esta (en pseudocodigo):</p>
<p><strong>mientras verdadero<br /> recupera mensajes nuevos<br /> muestra mensajes nuevos<br />fin del mientras</strong></p>
<p>haría que cada vez que un mensaje nuevo apareciese se enviase al navegador y este lo mostrara instantaneamente, con lo que habríamos conseguido que fuese el tiempo real.</p>
<p>Parar lograr este planteamiento en php tenemos que seguir los siguientes pasos (he reducido su código para simplificarlo):</p>
<p><strong>ob_start();</strong></p>
<p>Que activa el tratamiento del buffer en php</p>
<p><strong>set_time_limit(0);</strong></p>
<p>Indica al motor de php que el script nunca debe caducar a pesar de lo que dure.</p>
<p><strong><br />for(;;)<br />{<br /></strong></p>
<p>Este es el bucle que constantemente se va repitiendo.</p>
<p><strong><br />$rs=mysql_query(&#8220;SELECT * FROM chat_mensajes WHERE IDMensaje&gt;&#8217;&#8221; . $id . &#8220;&#8216; AND WEEK(DatFecha,1)=WEEK(NOW(),1) AND YEAR(DatFecha)=YEAR(NOW()) ORDER BY IDMensaje&#8221;)<br />or die (&#8220;No se puede realizar la consulta&#8221;);<br /></strong></p>
<p>En mi caso guardo los mensajes en una base de datos mysql, por lo que con la consulta SQL compruebo aquellos mensajes cuyo ID sea mayor que el último ID de mensaje que se ha mostrado (solo aquellos dentro de la semana actual del año en curso).</p>
<p><strong><br />if(mysql_num_rows($rs)&gt;0)<br />{<br /> while($fila=mysql_fetch_array($rs,MYSQL_ASSOC)) {<br /></strong></p>
<p>Compruebo si hay nuevos mensajes y los recorro.</p>
<p><strong><br />$id=$fila["IDMensaje"];<br /></strong></p>
<p>Voy actualizando la variable <em>id</em> para que contenga al final el último ID y así en la siguiente pasada del bucle solo recoger los últimos mensajes escritos a partir del indicado.</p>
<p><strong><br />echo &#8220;&lt;div&gt;\n&#8221;;<br />echo &#8220;&lt;span&gt;&#8221; . $fila["DatFecha"] . &#8221; &#8221; . &#8220;&lt;/span&gt;&#8221;;<br />echo &#8220;&lt;span&gt;&#8221; . $fila["StrUsuario"] . &#8220;&amp;gt;&lt;/span&gt;&#8221;;<br />echo &#8220;&lt;span&gt;&#8221; . $fila["StrMensaje"] . &#8220;&lt;/span&gt;&#8221;;<br />echo &#8220;&lt;/div&gt;\n&#8221;;<br />}<br /></strong></p>
<p>Se va mostrando el contenido de los mensajes (fecha, remitente y mensaje).</p>
<p><strong><br />echo &#8220;&lt;script&gt;scrollTo(0,999999999);&lt;/script&gt;\n&#8221;;<br />ob_flush();<br />flush();   <br />}<br /></strong></p>
<p>Con un pequeño truco en javascript logramos desplazar la ventana del navegador siempre hasta el final del contenido. A continuacuón vaciamos el buffer hacia el navegador del cliente.</p>
<p><strong><br />sleep(1);<br />}<br /></strong></p>
<p>Para no recargar mucho el servidor mysql haciendo constantemente consultas, pausamos durante un segundo la ejecución para después continuar con la siguiente iteración del bucle.</p>
<p>Quizá penseis que esta solución recarga mucho el servidor (tanto el web como el de mysql), pero el impacto es mínimo y si teneis un hosting esto os ahorrará ancho de banda puesto que gasta más por usuario el estar haciendo peticiones al servidor web cada X tiempo que una sola petición que dure eternamente (solo gasta lo que envia, como una petición normal); en cuanto al servidor mysql si este esta en localhost (como el 99% de los hosting) el impacto es mínimo porque no consume ningún recurso de red, además de que el propio mysql es rapídisimo y eficiente haciendo las consultas y no mermará el rendimiento por estar haciendo una cada segundo por cada usuario. Sin embargo si no quereis usar mysql, podeis usar ficheros (<strong>fopen</strong>) o bién memoria compartida (<strong>Shmop</strong>). Por supuesto esto no es la panacea, pero para cosas pequeñas (20 personas a la vez) si puede ir bién tenerlo así montado.</p>
<p>En la web en la que colaboro <a href="http://www.starwarsspanishstuff.info/webchat" target="_blank">tengo implementado</a> este sistema, que aunque lo tengo bastante desarollado, todavía tengo que mejorar ciertos aspectos de funcionalidad.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.sistemasorp.es/2005/11/01/webchat-en-tiempo-real-con-php-y-mysql/feed/</wfw:commentRss>
		<slash:comments>18</slash:comments>
		</item>
		<item>
		<title>Generar imágenes aleatorias con php y google</title>
		<link>http://www.sistemasorp.es/2005/09/06/generar-imagenes-aleatorias-con-php-y-google/</link>
		<comments>http://www.sistemasorp.es/2005/09/06/generar-imagenes-aleatorias-con-php-y-google/#comments</comments>
		<pubDate>Tue, 06 Sep 2005 12:33:00 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://www.sistemasorp.es/2005/09/06/generar-imagenes-aleatorias-con-php-y-google/</guid>
		<description><![CDATA[Hace poco me planteé meter una sección de imágenes aleatorias en la web que estoy administrando junto con un amigo sobre coleccionismo español de la guerra de las galaxias. El caso es que el hecho de tener un montón de imágenes almacenadas no es la mejor solución para un hosting si no tienes mucho espacio, [...]]]></description>
			<content:encoded><![CDATA[<p>Hace poco me planteé meter una sección de imágenes aleatorias en la <a href="http://www.starwarsspanishstuff.info" target="_blank">web</a> que estoy administrando junto con un amigo sobre coleccionismo español de la guerra de las galaxias.</p>
<p>El caso es que el hecho de tener un montón de imágenes almacenadas no es la mejor solución para un hosting si no tienes mucho espacio, por lo que se me ocurrió recurrir a la sección de imágenes de google. En esta sección se muestran en formato thumbnail (imágen pequeña de referencia) todas las imágenes de las páginas web que en su día indexó google, por lo que además de tener un vasto repertorio de imágenes, todas ellas estan asociadas al texto de la web a la que pertenecen. Así, si buscamos por palabras, podemos encontrar imágenes que concuerden con la búsqueda.</p>
<p>A mi me viene de lujo para mis intenciones, puesto que poniendo <em>star wars</em> en el cuadro de texto de la sección de imágenes de google aparecen algo menos de un millón de resultados. Añadiendo que la sección que quería poner en la web era más bién pequeña, las imágenes thumbnail de google son perfectas en cuanto a dimensiones para que quepa en la sección de la web.</p>
<p>Ahora bién, ¿como hacer para que los thumnails que google ha generado salgan en la web como propios?&#8230;Pues gracias a php puedo leer el contenido de las urls y mostrarlo con una cabecera apropiada como si fuera una imagen normal y corriente.</p>
<p>1-Una imagen en HTML se hace con la etiqueta <em>IMG</em> y el atributo <em>src</em>. En mi caso la imágen aletoria de la web debería apuntar siempre a un mismo sitio ya que es el propio php quien mostraría una imagen distinta cada vez. Por lo que en la web si os habeis fijado aparece:</p>
<p><strong>&lt;img src=&#8221;aleatorio.php&#8221; alt=&#8221;Imagen aleatoria (Gracias a Google Images)&#8221;&gt;</strong></p>
<p>Que indica al navegador que debe mostrar la imagen que genera la página <em>aleatoria.php</em> (con esto os podeis imaginar que los nombres de los ficheros le importan un pimiento al navegador, solo le interesa las cabeceras que devuelva el servidor)</p>
<p>2-Ahora tenemos que programar el código que recupere y muestre los bytes de la imagen que se quiere escoger al azar. Para ello debemos coger las imagenes de google, pero ¿como?. Pues antes de mostrar nada de código, voy a explicar muy por encima como funciona la sección de imágenes de google:</p>
<p>Voy a <a href="http://images.google.es/" target="_blank">http://images.google.es/</a> y pongo como busqueda <em>star wars</em></p>
<p>Me salen 20 imágenes, y unos enlaces para ir avanzando en el catálogo de imágenes. Sin embargo los thumbnails que aparecen son todavía un poco grandes para la sección de la web, por lo que elijo la opción <em>Medianas</em>, ahora pulsaremos por ejemplo sobre la página 3 del catálogo. Si os fijais a medida que he ido pulsando enlaces la url aparece con más datos:</p>
<p><em>http://images.google.es/images?q=star+wars&amp;imgsz=small%7Cmedium%7Clarge%7Cxlarge&amp;svnum=10&amp;hl=es&amp;lr=&amp;start=40&amp;sa=N</em></p>
<p>Esto es lo que nos servirá como primer punto para la busqueda de imágenes relacionadas con un tema determinado. Si os fiajis en los parámetros de la url está la letra <strong>q</strong>, donde se almacena el criterio de la búsqueda (en mi caso <em>star+wars</em>); <strong>imgsz</strong>, que indica el tamaño de las imágenes a buscar (puede ser también <em>xxlarge </em>e <em>icon</em>, aunque en mi caso es small%7Cmedium%7Clarge%7Cxlarge); <strong>svnum</strong> que no se para que sirve, ya que si lo quito funciona igual; <strong>hl</strong> para el idioma de los resultados; <strong>lr</strong> que tampoco sé para que sirve, <strong>start</strong> que indica desde que indice empezar, este es muy importante ya que aqui usaremos el primer número aleatorio; <strong>sa</strong>=N que no se para que sirve.</p>
<p>Como os comentaba, con <strong>start</strong> se puede indicar desde que índice de las imágenes empezar a mostrar: 0 sería desde la primera página, 20 desde la segunda página, 40 desde la tercera, etc. También podemos poner valores intermedios, pero yo sigo el camino de google con sus enlaces.</p>
<p>Una vez que ya podemos elegir que página de imágenes queremos cargar, ya solo queda elegir que imagen de las 20 que aparece en esa página mostrar, momento por el cual debemos usar el segundo número aleatorio. Pero claro, lo que nos interesa son las imágenes de google, no las originales a las que apunta el enlace de cada una de ellas. Por eso debemos recorrer el codigo fuente HTML de la página que hemos recuperado para ir etiqueta por etiqueta <em>IMG</em> hasta alcanzar el número aleatorio que habiamos solicitado. Sin embargo no podemos empezar desde el principio puesto que google tiene en su página un logo, unas imagenes de 1 pixel de grosor, etc. Es por ello que debemos comenzar a partir de un punto donde sepamos que a continuación todas las etiquetas IMG son las de los thumbnails. En mi caso uso la cadena &#8220;<em>Solamente se muestran las</em>&#8220;.</p>
<p>A partir de entónces, cuando ya obtengamos el atributo <em>src</em> de la etiqueta <em>IMG</em> requerida, ya podremos recuperar los bytes de la imagen thumbnail de google a través de su url. Posteriormente solo queda mostrarla a través del PHP.</p>
<p>El siguiente código fuente muestra como lo hacer lo que he comentado anteriormente desde una página php:</p>

<div class="wp_syntax"><div class="code"><pre class="php" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">&lt;?</span>
<span style="color: #666666; font-style: italic;">// Hacemos que nunca se cachee ninguna imagen</span>
<span style="color: #990000;">header</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;Expires: Mon, 26 Jul 1997 05:00:00 GMT&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #990000;">header</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;Last-Modified: &quot;</span> <span style="color: #339933;">.</span> <span style="color: #990000;">gmdate</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;D, d M Y H:i:s&quot;</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">.</span> <span style="color: #0000ff;">&quot; GMT&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #990000;">header</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;Cache-Control: no-store, no-cache, must-revalidate&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #990000;">header</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;Cache-Control: post-check=0, pre-check=0&quot;</span><span style="color: #339933;">,</span> <span style="color: #009900; font-weight: bold;">false</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #990000;">header</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;Pragma: no-cache&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #666666; font-style: italic;">//elegimos una sección al azar de las imagenes de google</span>
<span style="color: #000088;">$texto</span><span style="color: #339933;">=</span><span style="color: #0000ff;">&quot;&quot;</span><span style="color: #339933;">;</span>
<span style="color: #990000;">mt_srand</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#40;</span>double<span style="color: #009900;">&#41;</span><span style="color: #990000;">microtime</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">*</span><span style="color: #cc66cc;">1000000</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #000088;">$inicio</span> <span style="color: #339933;">=</span> <span style="color: #990000;">mt_rand</span><span style="color: #009900;">&#40;</span><span style="color: #cc66cc;">0</span><span style="color: #339933;">,</span><span style="color: #cc66cc;">20</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">*</span><span style="color: #cc66cc;">20</span><span style="color: #339933;">;</span>
<span style="color: #000088;">$url</span><span style="color: #339933;">=</span><span style="color: #0000ff;">&quot;http://images.google.es/images?q=star+wars&amp;imgsz=small%7Cmedium%7Clarge%7Cxlarge&amp;hl=es&amp;lr=&amp;start=<span style="color: #006699; font-weight: bold;">$inicio</span>&amp;sa=N&quot;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #666666; font-style: italic;">// abrimos la url generada dinamicamente</span>
<span style="color: #000088;">$fichero</span><span style="color: #339933;">=</span><span style="color: #990000;">fopen</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$url</span><span style="color: #339933;">,</span><span style="color: #0000ff;">&quot;r&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #b1b100;">while</span><span style="color: #009900;">&#40;</span><span style="color: #339933;">!</span><span style="color: #990000;">feof</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$fichero</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span>
<span style="color: #000088;">$texto</span><span style="color: #339933;">.=</span><span style="color: #990000;">fread</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$fichero</span><span style="color: #339933;">,</span><span style="color: #cc66cc;">1024</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #990000;">fclose</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$fichero</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #666666; font-style: italic;">// dentro de la página devuelta, elegimos una imagen al azar</span>
<span style="color: #000088;">$indice</span> <span style="color: #339933;">=</span> <span style="color: #990000;">mt_rand</span><span style="color: #009900;">&#40;</span><span style="color: #cc66cc;">1</span><span style="color: #339933;">,</span><span style="color: #cc66cc;">20</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #666666; font-style: italic;">// para ello debemos recorrer todas las etiquetas IMG desde una posición determinada</span>
<span style="color: #000088;">$posicion</span><span style="color: #339933;">=</span><span style="color: #990000;">strpos</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$texto</span><span style="color: #339933;">,</span><span style="color: #0000ff;">&quot;Solamente se muestran las&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #b1b100;">for</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$contador</span><span style="color: #339933;">=</span><span style="color: #cc66cc;">0</span><span style="color: #339933;">;</span><span style="color: #000088;">$contador</span><span style="color: #339933;">&lt;</span><span style="color: #000088;">$indice</span><span style="color: #339933;">;</span><span style="color: #000088;">$contador</span><span style="color: #339933;">++</span><span style="color: #009900;">&#41;</span>
<span style="color: #000088;">$posicion</span><span style="color: #339933;">=</span><span style="color: #990000;">strpos</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$texto</span><span style="color: #339933;">,</span><span style="color: #0000ff;">&quot;&lt;img&quot;</span><span style="color: #339933;">,</span><span style="color: #000088;">$posicion</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">+</span><span style="color: #cc66cc;">4</span><span style="color: #339933;">;</span>
<span style="color: #000088;">$posicion</span><span style="color: #339933;">=</span><span style="color: #990000;">strpos</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$texto</span><span style="color: #339933;">,</span><span style="color: #0000ff;">&quot;src=&quot;</span><span style="color: #339933;">,</span><span style="color: #000088;">$posicion</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #666666; font-style: italic;">// cogemos la url de esa imagen de thumbnail de google</span>
<span style="color: #000088;">$url</span><span style="color: #339933;">=</span><span style="color: #0000ff;">&quot;http://images.google.es&quot;</span> <span style="color: #339933;">.</span> <span style="color: #990000;">substr</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$texto</span><span style="color: #339933;">,</span><span style="color: #000088;">$posicion</span><span style="color: #339933;">+</span><span style="color: #cc66cc;">4</span><span style="color: #339933;">,</span><span style="color: #990000;">strpos</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$texto</span><span style="color: #339933;">,</span><span style="color: #0000ff;">&quot; &quot;</span><span style="color: #339933;">,</span><span style="color: #000088;">$posicion</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">-</span><span style="color: #000088;">$posicion</span><span style="color: #339933;">-</span><span style="color: #cc66cc;">4</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #000088;">$texto</span><span style="color: #339933;">=</span><span style="color: #0000ff;">&quot;&quot;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #666666; font-style: italic;">// la abrimos para recuperar su contenido</span>
<span style="color: #000088;">$fichero</span><span style="color: #339933;">=</span><span style="color: #990000;">fopen</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$url</span><span style="color: #339933;">,</span><span style="color: #0000ff;">&quot;r&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #b1b100;">while</span><span style="color: #009900;">&#40;</span><span style="color: #339933;">!</span><span style="color: #990000;">feof</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$fichero</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span>
<span style="color: #000088;">$texto</span><span style="color: #339933;">.=</span><span style="color: #990000;">fread</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$fichero</span><span style="color: #339933;">,</span><span style="color: #cc66cc;">1024</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #990000;">fclose</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$fichero</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #666666; font-style: italic;">// mostramos la cabecera acorde con el tipo de fichero</span>
<span style="color: #b1b100;">switch</span><span style="color: #009900;">&#40;</span><span style="color: #990000;">substr</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$url</span><span style="color: #339933;">,</span><span style="color: #990000;">strrpos</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$url</span><span style="color: #339933;">,</span><span style="color: #0000ff;">&quot;.&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span>
<span style="color: #009900;">&#123;</span>
<span style="color: #b1b100;">case</span> <span style="color: #0000ff;">&quot;.gif&quot;</span><span style="color: #339933;">:</span>
<span style="color: #990000;">header</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;Content-type: image/gif&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #b1b100;">break</span><span style="color: #339933;">;</span>
<span style="color: #b1b100;">case</span> <span style="color: #0000ff;">&quot;.png&quot;</span><span style="color: #339933;">:</span>
<span style="color: #990000;">header</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;Content-type: image/png&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #b1b100;">break</span><span style="color: #339933;">;</span>
<span style="color: #b1b100;">default</span><span style="color: #339933;">:</span>
<span style="color: #990000;">header</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;Content-type: image/jpeg&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #b1b100;">break</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span>
<span style="color: #666666; font-style: italic;">// y finalmente mostramos el contenido de la imágen recuperada</span>
<span style="color: #b1b100;">echo</span> <span style="color: #000088;">$texto</span><span style="color: #339933;">;</span>
<span style="color: #000000; font-weight: bold;">?&gt;</span></pre></div></div>

<p>Podeis ver un ejemplo de su funcionamiento en la web que os indicaba arriba o directamente en este enlace <a href="http://www.starwarsspanishstuff.info/aleatorio.php" target="_blank">http://www.starwarsspanishstuff.info/aleatorio.php</a>.</p>
<p>Recomiendo poner en el texto alternativo un reconocimiento a google.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.sistemasorp.es/2005/09/06/generar-imagenes-aleatorias-con-php-y-google/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>Ejecutar una variable</title>
		<link>http://www.sistemasorp.es/2005/07/28/ejecutar-una-variable/</link>
		<comments>http://www.sistemasorp.es/2005/07/28/ejecutar-una-variable/#comments</comments>
		<pubDate>Thu, 28 Jul 2005 16:04:00 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://www.sistemasorp.es/2005/07/28/ejecutar-una-variable/</guid>
		<description><![CDATA[Tal como se lee puede parecer algo un tanto extraño. Todo el mundo que programa usa las variables para leer o introducir datos en ellas (aunque a veces lo que se esta haciendo por debajo es realmente llamar a una función). El caso es que el C, y por extensión el C++ (ignoro si el [...]]]></description>
			<content:encoded><![CDATA[<p>Tal como se lee puede parecer algo un tanto extraño. Todo el mundo que programa usa las variables para leer o introducir datos en ellas (aunque a veces lo que se esta haciendo por debajo es realmente llamar a una función). El caso es que el C, y por extensión el C++ (ignoro si el C# tiene esta caracteristica) puede crear punteros a funciones. Estos punteros, como el resto, son una variable que contiene una dirección de memoria; sin embargo, su uso normal es asignarle el nombre de una función en vez de una variable, tal que así:</p>

<div class="wp_syntax"><div class="code"><pre class="c" style="font-family:monospace;"><span style="color: #993333;">typedef</span> <span style="color: #993333;">unsigned</span> <span style="color: #993333;">int</span> <span style="color: #009900;">&#40;</span><span style="color: #339933;">*</span>funcion<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#40;</span><span style="color: #993333;">const</span> <span style="color: #993333;">char</span> <span style="color: #339933;">*</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
funcion pepe<span style="color: #339933;">;</span>
pepe<span style="color: #339933;">=</span>strlen<span style="color: #339933;">;</span>
<span style="color: #000066;">printf</span><span style="color: #009900;">&#40;</span><span style="color: #ff0000;">&quot;Longitud de hola:%d<span style="color: #000099; font-weight: bold;">\n</span>&quot;</span><span style="color: #339933;">,</span>pepe<span style="color: #009900;">&#40;</span><span style="color: #ff0000;">&quot;hola&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p>Pero que pasaría si en vez de asignarle una función le asignamos una variable? Pues<br />
que el contenido de esa variable lo ejecutaría. Por supuesto, la variable no puede tener cualquier contenido; los bytes que contendría deberían ser codigo maquina. Por ejemplo el siguiente código en ensamblador:</p>

<div class="wp_syntax"><div class="code"><pre class="asm" style="font-family:monospace;"><span style="color: #00007f; font-weight: bold;">MOV</span> <span style="color: #00007f;">EAX</span><span style="color: #339933;">,</span><span style="color: #0000ff;">9</span>
<span style="color: #00007f; font-weight: bold;">RET</span></pre></div></div>

<p>traducido a codigo máquina del intel x86 sería:</p>
<blockquote><p>B8 09 00 00 00<br />
C3</p></blockquote>
<p>Por lo que si ejecutamos las siguientes lineas:</p>

<div class="wp_syntax"><div class="code"><pre class="c" style="font-family:monospace;"><span style="color: #993333;">typedef</span> <span style="color: #993333;">unsigned</span> <span style="color: #993333;">int</span> <span style="color: #009900;">&#40;</span><span style="color: #339933;">*</span>funcion<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#40;</span><span style="color: #993333;">void</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
funcion pepe<span style="color: #339933;">;</span>
<span style="color: #993333;">unsigned</span> <span style="color: #993333;">char</span> juan<span style="color: #009900;">&#91;</span><span style="color: #009900;">&#93;</span><span style="color: #339933;">=</span><span style="color: #009900;">&#123;</span><span style="color: #208080;">0xb8</span><span style="color: #339933;">,</span><span style="color: #0000dd;">9</span><span style="color: #339933;">,</span><span style="color: #0000dd;">0</span><span style="color: #339933;">,</span><span style="color: #0000dd;">0</span><span style="color: #339933;">,</span><span style="color: #0000dd;">0</span><span style="color: #339933;">,</span><span style="color: #208080;">0xc3</span><span style="color: #009900;">&#125;</span><span style="color: #339933;">;</span>
pepe<span style="color: #339933;">=</span><span style="color: #009900;">&#40;</span><span style="color: #993333;">unsigned</span> <span style="color: #993333;">int</span> <span style="color: #009900;">&#40;</span><span style="color: #339933;">*</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#40;</span><span style="color: #993333;">void</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#40;</span><span style="color: #993333;">void</span><span style="color: #339933;">*</span><span style="color: #009900;">&#41;</span>juan<span style="color: #339933;">;</span>
<span style="color: #000066;">printf</span><span style="color: #009900;">&#40;</span><span style="color: #ff0000;">&quot;Es un 9?:%d<span style="color: #000099; font-weight: bold;">\n</span>&quot;</span><span style="color: #339933;">,</span>pepe<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p>Lo que hemos hecho es llamar a una dirección de memoria que contenia una ristra de bytes, los cuales son significativos para el microprocesador. En el ejemplo hemos asignado al registro EAX (registro que almacena siempre lo que devuelve una función) el número 9 y a continuación ejecutamos un RET para retornar de la llamada de la función. Así hemos simulado una llamada a una función tal y como lo habría hecho el compilador, pudiendo incluso modificar el código (el contenido de la variable) en tiempo de ejecución sin problemas de violaciones de memoria o similares. Este código funciona tanto en Linux como en Windows siempre que sea un micro intel x86, aunque se puede usar en un motorola, power pc, o lo que querais siempre que conozcais el<br />
lenguaje maquina del micro.</p>
<p>Este artículo dará pie a otro mucho más avanzado sobre como lograr que un programa original pueda acceder a un web service sin que otros se aprovechen de esa información (si usar contraseñas ni nada parecido).</p>
]]></content:encoded>
			<wfw:commentRss>http://www.sistemasorp.es/2005/07/28/ejecutar-una-variable/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Por fin nos libramos de las patentes de software</title>
		<link>http://www.sistemasorp.es/2005/07/06/por-fin-nos-libramos-de-las-patentes-de-software/</link>
		<comments>http://www.sistemasorp.es/2005/07/06/por-fin-nos-libramos-de-las-patentes-de-software/#comments</comments>
		<pubDate>Wed, 06 Jul 2005 19:25:00 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://www.sistemasorp.es/2005/07/06/por-fin-nos-libramos-de-las-patentes-de-software/</guid>
		<description><![CDATA[Después de haber luchado incansablemente por que las patentes de software no salgan adelante, después de haber explicado sus contras, después de habernos llevado grandes disgustos y pequeñas alegrías, por fín puedo decir que la propuesta de patentes de software en Europa ha sido definitivamente derogada contundentemente por 648 votos a favor, 14 en contra [...]]]></description>
			<content:encoded><![CDATA[<p>Después de haber luchado incansablemente por que las patentes de software no salgan adelante, después de <a target="_blank" href="http://sistemasorp.blogspot.com/2004/05/las-patentes.html">haber explicado sus contras</a>, después de habernos llevado grandes disgustos y pequeñas alegrías, por fín puedo decir que la propuesta de patentes de software en Europa ha sido <a target="_blank" href="http://www.elmundo.es/navegante/2005/07/06/softlibre/1120638414.html">definitivamente derogada</a> contundentemente por 648 votos a favor, 14 en contra y 18 abstenciones.</p>
<p>¡¡¡ Estamos de Enhorabuena !!!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.sistemasorp.es/2005/07/06/por-fin-nos-libramos-de-las-patentes-de-software/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Wake On LAN y Magic Packet</title>
		<link>http://www.sistemasorp.es/2005/06/13/wake-on-lan-y-magic-packet/</link>
		<comments>http://www.sistemasorp.es/2005/06/13/wake-on-lan-y-magic-packet/#comments</comments>
		<pubDate>Mon, 13 Jun 2005 18:07:00 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://www.sistemasorp.es/2005/06/13/wake-on-lan-y-magic-packet/</guid>
		<description><![CDATA[Todos sabemos que podemos apagar el ordenador con un comando o bién con una combinación de pulsaciones de teclado o ratón, también hay programas que dado cierto evento hacen que se apague el sistema. Esto no tiene ningún misterio, pero&#8230; ¿y si se trata de encenderlo?. Puede que con el solo hecho de pulsar el [...]]]></description>
			<content:encoded><![CDATA[<p>Todos sabemos que podemos apagar el ordenador con un comando o bién con una combinación de pulsaciones de teclado o ratón, también hay programas que dado cierto evento hacen que se apague el sistema.</p>
<p>Esto no tiene ningún misterio, pero&#8230; ¿y si se trata de encenderlo?. Puede que con el solo hecho de pulsar el botón de encendido de la cpu nos sea suficiente (a veces con pulsar un botón del teclado o mover el ratón), sin embargo cuando no estamos físicamente presentes la cosa cambia: un cibercafe donde es más cómodo encender todos los ordenadores a la vez, o encender un ordenador remoto que por las noches se apaga para ahorrar electricidad, etc. Antiguamente los ordenadores se apagaban y punto, pero desde que irrumpió en el mercado el formato <a href="http://en.wikipedia.org/wiki/ATX" target="_blank">ATX</a> de cajas y placas madre y con el estandar <a href="http://en.wikipedia.org/wiki/Advanced_Configuration_and_Power_Interface" target="_blank">ACPI</a> la cosa no ha hecho más que facilitarnos las cosas: ahora gracias a esos dos estandares somos capaces de apagar el ordenador por software, apagar el equipo ordenadamente por hardware, suspender, volver a reactivar, volver a encender, etc. En la parte que nos toca hay unos eventos que son capaces de encender un ordenador cuando este está apagado, y para la gestión remota de ese encendido se puede usar unos metodos denominados <em>wake on ring, wake on modem (por modem)</em> o <em>wake on lan (por red)</em>.</p>
<p>Este artículo se centra en el método <a href="http://en.wikipedia.org/wiki/Wake-on-LAN" target="_blank">Wake On Lan</a> (+ o &#8211; despertar por red). Este sistema se basa en que un ordenador cuando se apaga, no lo hace totalmente, sino que la fuente de alimentación sigue alimentando a la placa madre, y esta puede gestionar con muy bajo consumo los eventos que se den, como por ejemplo, encender el ordenador cuando recibe un paquete especial por la tarjeta de red. Este paquete, conocido como <em>Magic Packet </em>es muy simple y su formato consiste en 6 bytes con valor hexadecimal FF y otros 16 grupos de 6 bytes con la dirección <a href="http://en.wikipedia.org/wiki/MAC_address" target="_blank">MAC</a> de la tarjeta de red. Da igual en que protocolo se envié ese paquete (IPX, TCP/IP, etc), con tal de que se envíe por toda la red. Así si se quiere encender un ordenador con una MAC 01:02:03.04:05:06 se enviaría un paquete con estos bytes en hexadecimal:<br />
<em><br />
FFFFFFFFFFFF<br />
010203040506010203040506010203040506010203040506<br />
010203040506010203040506010203040506010203040506<br />
010203040506010203040506010203040506010203040506<br />
010203040506010203040506010203040506010203040506<br />
</em><br />
El paquete debe enviarse a toda la red, por lo que hay que intentar que sea con el protocolo que se haga, este debe permitir enviar paquetes <a href="http://en.wikipedia.org/wiki/Broadcast_address" target="_blank">broadcast</a>. Esto normalmente se puede conseguir con el protocolo IP, ya que poniendo como destinatario la dirección IP 255.255.255.255 debería llegar a todos los nodos de todas las redes que lo permitan. El TCP o UDP que venga por encima no es importante, aunque personalmente prefiero el UDP por no ser orientado a conexión. Por encima del UDP vendrá el magic packet. A continuación pongo un ejemplo de codigo fuente en varios lenguajes de programación para que podais probarlo (son tan cortos que no hacen falta comentarlos, tampoco tienen gestión de errores para su simplicidad), en vuestro caso solo tendrías que modificar el puerto (1976) y la dirección MAC (01:02:03:04:05:06):</p>
<p><strong>C para Linux/Unix y Windows</strong></p>

<div class="wp_syntax"><div class="code"><pre class="c" style="font-family:monospace;"><span style="color: #339933;">#ifdef WIN32</span>
 <span style="color: #339933;">#include &lt;stdio.h&gt;</span>
 <span style="color: #339933;">#include &lt;winsock2.h&gt;</span>
<span style="color: #339933;">#else</span>
        <span style="color: #339933;">#include &lt;sys/types.h&gt;</span>
        <span style="color: #339933;">#include &lt;sys/socket.h&gt;</span>
        <span style="color: #339933;">#include &lt;netinet/in.h&gt;</span>
<span style="color: #339933;">#endif</span>
<span style="color: #993333;">void</span> main<span style="color: #009900;">&#40;</span><span style="color: #993333;">void</span><span style="color: #009900;">&#41;</span>
<span style="color: #009900;">&#123;</span>
 <span style="color: #993333;">int</span> conexion<span style="color: #339933;">;</span>
 <span style="color: #993333;">struct</span> sockaddr_in direccion<span style="color: #339933;">;</span>
 <span style="color: #993333;">unsigned</span> <span style="color: #993333;">char</span> buffer<span style="color: #009900;">&#91;</span><span style="color: #0000dd;">102</span><span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span>
 <span style="color: #993333;">unsigned</span> <span style="color: #993333;">char</span> mac<span style="color: #009900;">&#91;</span><span style="color: #009900;">&#93;</span><span style="color: #339933;">=</span><span style="color: #009900;">&#123;</span><span style="color: #208080;">0x01</span><span style="color: #339933;">,</span><span style="color: #208080;">0x02</span><span style="color: #339933;">,</span><span style="color: #208080;">0x03</span><span style="color: #339933;">,</span><span style="color: #208080;">0x04</span><span style="color: #339933;">,</span><span style="color: #208080;">0x5</span><span style="color: #339933;">,</span><span style="color: #208080;">0x06</span><span style="color: #009900;">&#125;</span><span style="color: #339933;">;</span>
 <span style="color: #993333;">int</span> valor<span style="color: #339933;">=</span><span style="color: #0000dd;">1</span><span style="color: #339933;">,</span>contador<span style="color: #339933;">;</span>
<span style="color: #339933;">#ifdef WIN32</span>
    WSADATA wsaData<span style="color: #339933;">;</span>
    WSAStartup<span style="color: #009900;">&#40;</span> MAKEWORD<span style="color: #009900;">&#40;</span> <span style="color: #0000dd;">2</span><span style="color: #339933;">,</span> <span style="color: #0000dd;">2</span> <span style="color: #009900;">&#41;</span><span style="color: #339933;">,</span> <span style="color: #339933;">&amp;</span>wsaData <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #339933;">#endif</span>
 <span style="color: #b1b100;">for</span><span style="color: #009900;">&#40;</span>contador<span style="color: #339933;">=</span><span style="color: #0000dd;">0</span><span style="color: #339933;">;</span>contador<span style="color: #339933;">&lt;</span><span style="color: #0000dd;">6</span><span style="color: #339933;">;</span>contador<span style="color: #339933;">++</span><span style="color: #009900;">&#41;</span>
  buffer<span style="color: #009900;">&#91;</span>contador<span style="color: #009900;">&#93;</span><span style="color: #339933;">=</span><span style="color: #208080;">0xff</span><span style="color: #339933;">;</span>
 <span style="color: #b1b100;">for</span><span style="color: #009900;">&#40;</span>contador<span style="color: #339933;">=</span><span style="color: #0000dd;">6</span><span style="color: #339933;">;</span>contador<span style="color: #339933;">&lt;</span><span style="color: #0000dd;">102</span><span style="color: #339933;">;</span>contador<span style="color: #339933;">+=</span><span style="color: #0000dd;">6</span><span style="color: #009900;">&#41;</span>
  memmove<span style="color: #009900;">&#40;</span><span style="color: #339933;">&amp;</span>buffer<span style="color: #009900;">&#91;</span>contador<span style="color: #009900;">&#93;</span><span style="color: #339933;">,</span>mac<span style="color: #339933;">,</span><span style="color: #0000dd;">6</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
 memset<span style="color: #009900;">&#40;</span>direccion.<span style="color: #202020;">sin_zero</span><span style="color: #339933;">,</span><span style="color: #0000dd;">0</span><span style="color: #339933;">,</span><span style="color: #0000dd;">8</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
 direccion.<span style="color: #202020;">sin_family</span><span style="color: #339933;">=</span>AF_INET<span style="color: #339933;">;</span>
 direccion.<span style="color: #202020;">sin_addr</span>.<span style="color: #202020;">s_addr</span><span style="color: #339933;">=</span>htonl<span style="color: #009900;">&#40;</span>INADDR_BROADCAST<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
 direccion.<span style="color: #202020;">sin_port</span><span style="color: #339933;">=</span>htons<span style="color: #009900;">&#40;</span><span style="color: #0000dd;">1976</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
 conexion<span style="color: #339933;">=</span>socket<span style="color: #009900;">&#40;</span>AF_INET<span style="color: #339933;">,</span>SOCK_DGRAM<span style="color: #339933;">,</span><span style="color: #0000dd;">0</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
 valor<span style="color: #339933;">=</span>setsockopt<span style="color: #009900;">&#40;</span>conexion<span style="color: #339933;">,</span> SOL_SOCKET<span style="color: #339933;">,</span> SO_BROADCAST<span style="color: #339933;">,</span> <span style="color: #009900;">&#40;</span><span style="color: #993333;">char</span> <span style="color: #339933;">*</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">&amp;</span>valor<span style="color: #339933;">,</span> <span style="color: #993333;">sizeof</span><span style="color: #009900;">&#40;</span><span style="color: #993333;">int</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
 sendto<span style="color: #009900;">&#40;</span>conexion<span style="color: #339933;">,</span><span style="color: #009900;">&#40;</span><span style="color: #993333;">char</span> <span style="color: #339933;">*</span><span style="color: #009900;">&#41;</span>buffer<span style="color: #339933;">,</span><span style="color: #0000dd;">102</span><span style="color: #339933;">,</span><span style="color: #0000dd;">0</span><span style="color: #339933;">,</span><span style="color: #009900;">&#40;</span><span style="color: #993333;">struct</span> sockaddr <span style="color: #339933;">*</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">&amp;</span>direccion<span style="color: #339933;">,</span><span style="color: #993333;">sizeof</span><span style="color: #009900;">&#40;</span><span style="color: #993333;">struct</span> sockaddr_in<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #339933;">#ifdef WIN32</span>
 WSACleanup<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #339933;">#endif</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p><strong>Perl</strong></p>

<div class="wp_syntax"><div class="code"><pre class="perl" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">use</span> strict<span style="color: #339933;">;</span>
<span style="color: #000000; font-weight: bold;">use</span> IO<span style="color: #339933;">::</span><span style="color: #006600;">Socket</span><span style="color: #339933;">::</span><span style="color: #006600;">INET</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #b1b100;">my</span> <span style="color: #0000ff;">$socket</span><span style="color: #339933;">;</span>
<span style="color: #b1b100;">my</span> <span style="color: #0000ff;">$msg</span><span style="color: #339933;">;</span>
<span style="color: #b1b100;">my</span> <span style="color: #0000ff;">$contador</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #0000ff;">$socket</span><span style="color: #339933;">=</span><span style="color: #000000; font-weight: bold;">new</span> IO<span style="color: #339933;">::</span><span style="color: #006600;">Socket</span><span style="color: #339933;">::</span><span style="color: #006600;">INET</span><span style="color: #339933;">-&gt;</span><span style="color: #006600;">new</span><span style="color: #009900;">&#40;</span>PeerPort<span style="color: #339933;">=&gt;</span><span style="color: #cc66cc;">1976</span><span style="color: #339933;">,</span>
        Proto<span style="color: #339933;">=&gt;</span><span style="color: #ff0000;">'udp'</span><span style="color: #339933;">,</span>
        PeerAddr<span style="color: #339933;">=&gt;</span><span style="color: #ff0000;">'255.255.255.255'</span><span style="color: #339933;">,</span>
        Broadcast<span style="color: #339933;">=&gt;</span><span style="color: #cc66cc;">1</span>
<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #0000ff;">$msg</span><span style="color: #339933;">=</span><span style="color: #ff0000;">&quot;&quot;</span><span style="color: #339933;">;</span>
<span style="color: #b1b100;">for</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">$contador</span><span style="color: #339933;">=</span><span style="color: #cc66cc;">0</span><span style="color: #339933;">;</span><span style="color: #0000ff;">$contador</span><span style="color: #339933;">&lt;</span><span style="color: #cc66cc;">6</span><span style="color: #339933;">;</span><span style="color: #0000ff;">$contador</span><span style="color: #339933;">++</span><span style="color: #009900;">&#41;</span>
<span style="color: #009900;">&#123;</span>
        <span style="color: #0000ff;">$msg</span><span style="color: #339933;">.=</span><span style="color: #ff0000;">&quot;<span style="color: #000099; font-weight: bold;">\x</span>ff&quot;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span>
<span style="color: #b1b100;">for</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">$contador</span><span style="color: #339933;">=</span><span style="color: #cc66cc;">0</span><span style="color: #339933;">;</span><span style="color: #0000ff;">$contador</span><span style="color: #339933;">&lt;</span><span style="color: #cc66cc;">16</span><span style="color: #339933;">;</span><span style="color: #0000ff;">$contador</span><span style="color: #339933;">++</span><span style="color: #009900;">&#41;</span>
<span style="color: #009900;">&#123;</span>
        <span style="color: #0000ff;">$msg</span><span style="color: #339933;">.=</span><span style="color: #ff0000;">&quot;<span style="color: #000099; font-weight: bold;">\x</span>01<span style="color: #000099; font-weight: bold;">\x</span>02<span style="color: #000099; font-weight: bold;">\x</span>03<span style="color: #000099; font-weight: bold;">\x</span>04<span style="color: #000099; font-weight: bold;">\x</span>05<span style="color: #000099; font-weight: bold;">\x</span>06&quot;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span>
<span style="color: #0000ff;">$socket</span><span style="color: #339933;">-&gt;</span><span style="color: #006600;">send</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">$msg</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p><strong>Java</strong></p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">import</span> <span style="color: #006699;">java.net.*</span><span style="color: #339933;">;</span>
<span style="color: #000000; font-weight: bold;">import</span> <span style="color: #006699;">java.io.IOException</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> Wol
<span style="color: #009900;">&#123;</span>
 <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">static</span> <span style="color: #000066; font-weight: bold;">void</span> main<span style="color: #009900;">&#40;</span><span style="color: #003399;">String</span> args<span style="color: #009900;">&#91;</span><span style="color: #009900;">&#93;</span><span style="color: #009900;">&#41;</span>
 <span style="color: #009900;">&#123;</span>
                <span style="color: #000066; font-weight: bold;">byte</span> mac<span style="color: #009900;">&#91;</span><span style="color: #009900;">&#93;</span><span style="color: #339933;">=</span><span style="color: #009900;">&#123;</span>0x01,0x02,0x03,0x04,0x05,0x06<span style="color: #009900;">&#125;</span><span style="color: #339933;">;</span>
  <span style="color: #000066; font-weight: bold;">byte</span> buffer<span style="color: #009900;">&#91;</span><span style="color: #009900;">&#93;</span><span style="color: #339933;">=</span><span style="color: #000000; font-weight: bold;">new</span> <span style="color: #000066; font-weight: bold;">byte</span><span style="color: #009900;">&#91;</span><span style="color: #cc66cc;">102</span><span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span>
  <span style="color: #000066; font-weight: bold;">byte</span> contador<span style="color: #339933;">;</span>
&nbsp;
  <span style="color: #000000; font-weight: bold;">for</span><span style="color: #009900;">&#40;</span>contador<span style="color: #339933;">=</span><span style="color: #cc66cc;">0</span><span style="color: #339933;">;</span>contador<span style="color: #339933;">&lt;</span><span style="color: #cc66cc;">6</span><span style="color: #339933;">;</span>contador<span style="color: #339933;">++</span><span style="color: #009900;">&#41;</span>
   buffer<span style="color: #009900;">&#91;</span>contador<span style="color: #009900;">&#93;</span><span style="color: #339933;">=</span><span style="color: #009900;">&#40;</span><span style="color: #000066; font-weight: bold;">byte</span><span style="color: #009900;">&#41;</span>0xff<span style="color: #339933;">;</span>
  <span style="color: #000000; font-weight: bold;">for</span><span style="color: #009900;">&#40;</span>contador<span style="color: #339933;">=</span><span style="color: #cc66cc;">6</span><span style="color: #339933;">;</span>contador<span style="color: #339933;">&lt;</span><span style="color: #cc66cc;">102</span><span style="color: #339933;">;</span>contador<span style="color: #339933;">+=</span><span style="color: #cc66cc;">6</span><span style="color: #009900;">&#41;</span>
   <span style="color: #003399;">System</span>.<span style="color: #006633;">arraycopy</span><span style="color: #009900;">&#40;</span>mac,<span style="color: #cc66cc;">0</span>,buffer,contador,<span style="color: #cc66cc;">6</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
  <span style="color: #000000; font-weight: bold;">try</span>
  <span style="color: #009900;">&#123;</span>
   <span style="color: #003399;">DatagramSocket</span> udp<span style="color: #339933;">=</span><span style="color: #000000; font-weight: bold;">new</span> <span style="color: #003399;">DatagramSocket</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
   udp.<span style="color: #006633;">setBroadcast</span><span style="color: #009900;">&#40;</span><span style="color: #000066; font-weight: bold;">true</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
   udp.<span style="color: #006633;">send</span><span style="color: #009900;">&#40;</span><span style="color: #000000; font-weight: bold;">new</span> <span style="color: #003399;">DatagramPacket</span><span style="color: #009900;">&#40;</span>buffer,<span style="color: #cc66cc;">102</span>,<span style="color: #003399;">InetAddress</span>.<span style="color: #006633;">getByName</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;255.255.255.255&quot;</span><span style="color: #009900;">&#41;</span>,<span style="color: #cc66cc;">1976</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
  <span style="color: #009900;">&#125;</span>
  <span style="color: #000000; font-weight: bold;">catch</span><span style="color: #009900;">&#40;</span>java.<span style="color: #006633;">net</span>.<span style="color: #003399;">SocketException</span> se<span style="color: #009900;">&#41;</span>
  <span style="color: #009900;">&#123;</span>
   <span style="color: #003399;">System</span>.<span style="color: #006633;">err</span>.<span style="color: #006633;">println</span><span style="color: #009900;">&#40;</span>se<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
  <span style="color: #009900;">&#125;</span>
  <span style="color: #000000; font-weight: bold;">catch</span><span style="color: #009900;">&#40;</span>java.<span style="color: #006633;">net</span>.<span style="color: #003399;">UnknownHostException</span> ue<span style="color: #009900;">&#41;</span>
  <span style="color: #009900;">&#123;</span>
   <span style="color: #003399;">System</span>.<span style="color: #006633;">err</span>.<span style="color: #006633;">println</span><span style="color: #009900;">&#40;</span>ue<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
  <span style="color: #009900;">&#125;</span>
  <span style="color: #000000; font-weight: bold;">catch</span><span style="color: #009900;">&#40;</span>java.<span style="color: #006633;">io</span>.<span style="color: #003399;">IOException</span> ie<span style="color: #009900;">&#41;</span>
  <span style="color: #009900;">&#123;</span>
   <span style="color: #003399;">System</span>.<span style="color: #006633;">err</span>.<span style="color: #006633;">println</span><span style="color: #009900;">&#40;</span>ie<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
  <span style="color: #009900;">&#125;</span>
 <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p><strong>Visual Basic</strong> (Para que funcione debeis insertar un control Winsock)</p>

<div class="wp_syntax"><div class="code"><pre class="vb" style="font-family:monospace;"><span style="color: #000080;">Dim</span> buffer() <span style="color: #000080;">As</span> <span style="color: #000080;">Byte</span>
<span style="color: #000080;">Dim</span> contador <span style="color: #000080;">As</span> <span style="color: #000080;">Byte</span>
&nbsp;
<span style="color: #000080;">ReDim</span> buffer(101) <span style="color: #000080;">As</span> <span style="color: #000080;">Byte</span>
<span style="color: #000080;">For</span> contador = 0 <span style="color: #000080;">To</span> 5
 buffer(contador) = &amp;HFF
<span style="color: #000080;">Next</span>
<span style="color: #000080;">For</span> contador = 6 <span style="color: #000080;">To</span> 101 <span style="color: #000080;">Step</span> 6
 buffer(contador) = &amp;H1
 buffer(contador + 1) = &amp;H2
 buffer(contador + 2) = &amp;H3
 buffer(contador + 3) = &amp;H4
 buffer(contador + 4) = &amp;H5
 buffer(contador + 5) = &amp;H6
<span style="color: #000080;">Next</span>
Winsock1.Protocol = sckUDPProtocol
Winsock1.RemoteHost = <span style="color: #800000;">&quot;255.255.255.255&quot;</span>
Winsock1.RemotePort = 1976
Winsock1.SendData buffer</pre></div></div>

<p>Por supuesto no hay método que sirva para marcar todas las tarjetas a la vez, así que habrá que ir una por una mandando el magic packet para que se vaya encendiendo cada ordenador. La tarjeta de red de cada ordenador apagado compara todos los paquetes que le llegan del tráfico de red para ver si contiene 16 veces su dirección MAC y así mandar a la placa madre que encienda el ordenador.</p>
<p>Las tarjetas de red que vengan incorporadas ya de fábrica en la placa madre ya tienen esta función activada. Sin embargo las que estan sueltas en ranuras PCI o ISA, deben:<br />
1) Permitir el wake on lan (no todas tienen un firware con esa posibilidad)<br />
2) La placa madre debe tener un conector de 3 pines que permita este evento.<br />
3) Un cable que vaya desde la tarjeta hasta la placa madre.<br />
En ambos casos se debe activar en la BIOS el mantenimiento de energía y posteriormente el evento WAKE ON LAN.</p>
<p>En mi portatil no puedo probar esta característica (cuando se apaga este, la tarjeta ethernet incorporada también se apaga). En el ordenador de sobremesa no me ha funcionado (tampoco funcionan eventos como el de encender el ordenador con una pulsación del teclado) y con el servidor me ha funcionado perfectamente.</p>
<p>El Magic Packet también se puede hacer desde Internet:<br />
Si teneis conexión directa solo debeis modificar vuestro programa para que apunte a vuestra IP pública de Internet (si no es fija podeis usar cosas como <a href="http://www.dyndns.org/" target="_blank">dyndns</a>).<br />
Si no teneis conexión directa o no quereis usar un programa, podeis hacerlo desde <a href="http://www.majoroak.f2s.com/tim/wol/html.php" target="_blank">aquí</a>.<br />
Sin embargo, a no ser que tengais un router que este conectado a Internet y donde podais poner rutas estáticas con IP, puertos y direcciones MAC no podreis hacerlo funcionar, ya que el router (como el mio) borra de la tabla <a href="http://en.wikipedia.org/wiki/Address_Resolution_Protocol" target="_blank">arp</a> las relaciones MAC/IP cuando detecta que no hay tráfico en una tarjeta determinada, por lo que aunque reciba un paquete que luego deba reenviar a una ip interna, lo ignora al no encontrarlo en la tabla; tampoco tiene opción para redireccionarlo como broadcast dentro de la red si no sabe que hacer con el.<strong></strong></p>
]]></content:encoded>
			<wfw:commentRss>http://www.sistemasorp.es/2005/06/13/wake-on-lan-y-magic-packet/feed/</wfw:commentRss>
		<slash:comments>14</slash:comments>
		</item>
	</channel>
</rss>
