Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

« Newer Snippets
Older Snippets »
Showing 1-10 of 11 total  RSS 

One-line web server in Ruby


# From: http://www.ntecs.de/blog/articles/2008/02/09/the-worlds-smallest-webserver
# Author: Michael Neumann
# ... point your browser to http://localhost:3125/etc/motd

ruby -rsocket -e 's=TCPServer.new(5**5);loop{_=s.accept;_<<"HTTP/1.0 200 OK\r\n\r\n#{File.read(_.gets.split[1])rescue nil}";_.close}'

Run TCPServer as a simple Web server

A TCPServer accepts incoming TCP connections. Here is a Web server that listens on a given port and returns the time.

require 'socket'
port = (ARGV[0] || 80).to_i
server = TCPServer.new('localhost', port)
while (session = server.accept)
  puts "Request: #{session.gets}"
  session.print "HTTP/1.1 200/OK\r\nContent-type: text/html\r\n\r\n"
  session.print "<html><body><h1>#{Time.now}</h1></body></html>\r\n"
  session.close
end

This code was copied from Programming Ruby: The Pragmatic Programmer's Guide [rubycentral.com] while looking for information on Ruby CGI global variables.

Getting a client's IP address with EventMachine

This is from, and by: http://nhw.pl/wp/2007/12/07/eventmachine-how-to-get-clients-ip-address/ .. I just wanted a more permanent reference as it's cool code.

EventMachine::run {
   EventMachine::open_datagram_socket $conf[:address],
                                 $conf[:udp_port], CustomServer
}

module CustomServer
   def receive_data d
      pp get_peername[2,6].unpack "nC4"
   end
end

[Ruby] Script/bot to send MediaWiki Recent Changes over UDP to a Campfire room

Requires the Tinder gem, and PHP on the server running MediaWiki must be compiled with --enable-sockets. The computer running the bot will also have to be open to the web - it can't be behind a firewall.

First, add this code to your MediaWiki LocalSettings.php, replacing the IP address with the IP of the server/computer running the bot, and the port to whatever you want to use (probably something above 40,000, but it's up to you):
$wgRC2UDPAddress = '69.178.6.244';
$wgRC2UDPPort = '41895';
$wgRC2UDPPrefix = "";


Now, you can run the bot! This is extremely hackish, because the retarded collective-mailing-list-coding system of the MediaWiki repos has somehow managed to code IRC color codes directly into their exported strings (at least with MediaWiki 1.2alpha, which is what I'm running right now).
You'll need to replace the new tinder definition with your subdomain on Campfire, the username and password with ones for the bot account you've created on your campfire room, and the room name with the room you want the updates to be sent to.
require 'rubygems'
require 'tinder'
require 'socket'
puts 'Dependencies loaded...'

campfire = Tinder::Campfire.new 'subdomain'
campfire.login 'email@domain.com', 'password'
exit unless room = campfire.find_room_by_name('Case Sensitive Room Name')
puts 'Campfire logged in...'

server = UDPSocket.new
exit unless server.bind('0.0.0.0', 41895)
puts 'Socket listening...'

loop do
  msg = server.recv(2048).gsub(/\003[\d]{0,2}/,'').chomp
  print "sending to room: #{msg.inspect}..."
  exit unless room.speak msg.to_s
  puts ' sent!'
end

Resolving a tinyURL to destination URL

Resolving a tinyURL to its original destination URL in a fastest way.

    < ?php

    // request like this http://<domain>/tinyurl.php?c=<tinyurl>

    $num = $_GET['c'];

    if($fp = fsockopen ("tinyurl.com", 80, $errno, $errstr, 30))
    {
    if ($fp) {
    fputs ($fp, "HEAD /$num HTTP/1.0\r\nHost: tinyurl.com\r\n\r\n");
    while (!feof($fp)) {$headers .= fgets ($fp,128);}
    fclose ($fp);
    }
    $arr1=explode("Location:",$headers);
    $arr=explode("\n",trim($arr1[1]));
    echo trim($arr[0]);
    }
    ?>


http://www.webforth.com/2007/07/resolving-tinyurls-to-the-desination-url

Send custom UDP packets in Ruby


From: http://www.ruby-forum.com/topic/124159
Author: Bill Kelly

For yet another nifty UDP snippet see Skype-Style Firewall Busting with Ruby and UDP.



require 'socket'

#abort "Usage: server_addr, server_port, cmd_str" unless ARGV.length == 3

UDP_RECV_TIMEOUT = 3  # seconds

def q2cmd(server_addr, server_port, cmd_str)
  resp, sock = nil, nil
  begin
   cmd = "\377\377\377\377#{cmd_str}\0"
    sock = UDPSocket.open
    sock.send(cmd, 0, server_addr, server_port)
    resp = if select([sock], nil, nil, UDP_RECV_TIMEOUT)
      sock.recvfrom(65536)
    end
    if resp
      resp[0] = resp[0][4..-1]  # trim leading 0xffffffff
    end
  rescue IOError, SystemCallError
  ensure
    sock.close if sock
  end
  resp ? resp[0] : nil
end

# your firewall has to allow communication with IP address 67.19.248.74 (port 27912)
#server, port, cmd = *ARGV
server = "tastyspleen.net"
port = 27912
cmd = "status"

result = q2cmd(server, port, cmd)
puts result


J2ME - getIPdevice

// Retrevie IP device

package org.socketdemo;

import javax.microedition.io.Connector;
import javax.microedition.io.SocketConnection;
import javax.microedition.lcdui.Alert;
import javax.microedition.lcdui.AlertType;
import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Displayable;
import javax.microedition.midlet.MIDlet;
import javax.microedition.midlet.MIDletStateChangeException;

public class SocketDEMO extends MIDlet implements CommandListener
{
	protected SocketDEMO midlet = this;
	
	private Alert info;
	
	protected void destroyApp(boolean value) throws MIDletStateChangeException
	{
		notifyDestroyed();
	}

	protected void pauseApp()
	{

	}

	protected void startApp() throws MIDletStateChangeException
	{
		new Thread()
		{
			public void run()
			{
				SocketConnection socket = null;
				
				try
				{
					socket = (SocketConnection) Connector.open("socket://193.204.114.233:13");
					
					socket.openInputStream();
					
					info = new Alert("Info", "Current IP: " + socket.getLocalAddress() + "\nPort: " + socket.getLocalPort(), null, AlertType.INFO);
					info.setTimeout(Alert.FOREVER);
					info.setCommandListener(midlet);
					
					getDisplay().setCurrent(info);
				}
				catch(Exception error)
				{
					info = new Alert("Info", "Current IP: N/A\nPort: N/A", null, AlertType.INFO);
					info.setTimeout(Alert.FOREVER);
					info.setCommandListener(midlet);
					
					getDisplay().setCurrent(info);
				}
				finally
				{
					if(socket != null)
					{
						try
						{
							socket.close();
						}
						catch(Exception error)
						{
							
						}
					}
				}
			}
		}.start();
	}
	
	protected Display getDisplay()
	{
		return Display.getDisplay(this);
	}

	public void commandAction(Command cmd, Displayable dsp)
	{
		if(cmd == Alert.DISMISS_COMMAND)
		{
			try
			{
				destroyApp(true);
			}
			catch(MIDletStateChangeException error)
			{
			
			}
		}
	}
}

Python - SendSMS over BT and AT

// Send SMS over Bluetooth (AT Command)

import bluetooth

sockfd = bluetooth.BluetoothSocket(bluetooth.RFCOMM)
sockfd.connect(('00:00:00:00:00:00', 1)) # BT Address
sockfd.send('ATZ\r')
sockfd.send('AT+CMGF=1\r')
sockfd.send('AT+CSCA="+393359609600"\r') # Client TIM ITA
sockfd.send('AT+CMGS="+39xxxxxxxxxx"\r') # TO PhoneNumber
sockfd.send('Messaggio da mandare...\n')
sockfd.send(chr(26)) # CTRL+Z
sockfd.close()

Windows socket demo program -- uses threads and stuff -- for stress testing the TCP stack

// I wrote this to find out if the claims made at http://laurentszyster.be/blog/tcp-stack-flaking-out/ is
// valid. I disagree with the opinions of the person who posted that TCP flakes out on Windows. I think
// his program has obvious bugs. This program proves that as long as you write your code properly
// the TCP connections do not break randomly. Similar bugs existed in Bittorrent apparently, and they fixed them.
// For more information visit http://sparebandwidth.blogspot.com/2006/08/more-on-tcp-flaking-out.html

#define BUFFER_SIZE 1000
#define SERVER_ADDR "127.0.0.1"
#define SERVER_PORT 9999
#define NUM_THREADS 1000
#define SEND_SOCK_BUFFER_SIZE 34000
#define RECV_SOCK_BUFFER_SIZE  34000
#define SERVER_RECV_SOCK_BUFFER_SIZE  34000
#define SERVER_SEND_SOCK_BUFFER_SIZE 34000
#define CLIENT_LIMIT 1000	/* how many times to send/recv in client */

#include <stdio.h>     
#define FD_SETSIZE  NUM_THREADS
#include <winsock.h>   
#include <stdlib.h>    

#define fatal_error(arg) {\
		fprintf(stderr,"total in %d out %d, %s: %d\n",		\
			total_bytes_received, total_bytes_sent,		\
			arg, WSAGetLastError()); fflush(stderr); exit(1); }
#define fatal_error2(arg)  { fprintf(stderr, "%s", arg); fflush(stderr); exit(1);}

int threads_all_done = 0;

struct thread_args {
	int id;
	int server_sock;
	struct sockaddr_in server_addr;
};

void *client_thread(void *args)
{
	struct thread_args *client_thread_arg;
	struct sockaddr_in server_addr;
	int server_sock;
	int client_sock;
	int on = 1;
	int bytes_received, bytes_sent;
	int num_to_read;
	int total_bytes_received, total_bytes_sent;
	char buffer[BUFFER_SIZE];
	int size;
	int i;

	total_bytes_received = total_bytes_sent = 0;
	
	client_thread_arg = (struct thread_args *)args;
	memcpy(&server_addr, &client_thread_arg->server_addr,
	       sizeof(struct sockaddr_in));
	server_sock = client_thread_arg->server_sock;

	if ((client_sock = socket(PF_INET, SOCK_STREAM,
				  IPPROTO_TCP)) < 0)
		fatal_error("socket() error in client thread");

	if (connect(client_sock, (struct sockaddr *)&server_addr,
		    sizeof(server_addr)) < 0)
		fatal_error("connect() error in client thread");

	/* wait for the server to send startup message */
	if ((bytes_received =
	     recv(client_sock, buffer, BUFFER_SIZE, 0)) < 0)
		fatal_error("recv() error in client thread");

	if (ioctlsocket(client_sock, FIONBIO, &on) < 0)
		fatal_error("FIONBIO error in client thread");

	size = SEND_SOCK_BUFFER_SIZE;
	if (setsockopt(client_sock, SOL_SOCKET, SO_SNDBUF, &size, sizeof(size)) < 0)
		fatal_error("SO_SNDBUF error in client thread");
	size = RECV_SOCK_BUFFER_SIZE;
	if (setsockopt(client_sock, SOL_SOCKET, SO_RCVBUF, &size, sizeof(size)) < 0)
		fatal_error("SO_RCVBUF error in client thread");
	
	for (i = 0; i < CLIENT_LIMIT ; i++) {
		int errno;
		
		if ((bytes_sent =
		     send(client_sock, buffer,
			  BUFFER_SIZE, 0)) != BUFFER_SIZE) {
			errno = WSAGetLastError();
			if (errno == WSAEWOULDBLOCK ||
				errno == WSAENOBUFS)
				continue;
			
			fatal_error("send() error in client thread");
		}
		total_bytes_sent += bytes_sent;

		num_to_read = 0;
		if (ioctlsocket(client_sock, FIONREAD, &num_to_read) < 0) 
			fatal_error("FIONREAD error in client thread");
		
		if (num_to_read == 0)
			continue;
		
		if ((bytes_received =
		     recv(client_sock, buffer, 
			  num_to_read >= BUFFER_SIZE ?
			  BUFFER_SIZE - 1 : num_to_read, 0)) <= 0)
			fatal_error("recv() error in client thread");
		total_bytes_received += bytes_received; 		
	}

	printf("thread %d total bytes received %d sent %d\n",
	       client_thread_arg->id, total_bytes_received, total_bytes_sent);

#if 0
	closesocket(client_sock);
#endif
	free(args);
}

void *starter_thread(void *args)
{
	HANDLE thread_handles[NUM_THREADS];
	DWORD thread_ids[NUM_THREADS];
	struct thread_args *client_thread_arg;
	int i;
	
	for (i = 0; i < NUM_THREADS; i++) {
		if ((client_thread_arg = 
		     (struct thread_args *)
		     malloc(sizeof(struct thread_args))) == 0) 
			fatal_error2("malloc client_thread_arg error");
		
		memcpy(client_thread_arg, args, sizeof(struct thread_args));
		client_thread_arg->id = i;

		if ((thread_handles[i] =
		     CreateThread(0, 0,
				  (LPTHREAD_START_ROUTINE) client_thread,
				  client_thread_arg, 0,
				  (LPDWORD)&thread_ids[i])) == 0) 
			fatal_error2("CreateThread for clients error");

		printf("created client thread %d\n", i); fflush(stdout);
	}
	free(args);
	args = 0;

	printf("%d threads created\n", NUM_THREADS); fflush(stdout);
	
	for (i = 0; i < NUM_THREADS; i++) 
		WaitForSingleObject(thread_handles[i], INFINITE);
	
	printf("all threads terminated\n"); fflush(stdout);

	threads_all_done = 1;
	
	ExitThread(0);
}

int main(void)
{
	int server_sock, client_sock;    
	struct sockaddr_in server_addr, client_addr; 
	int client_addr_len;
	unsigned short server_port;   
	char buffer[BUFFER_SIZE];    
	int bytes_received, total_bytes_received; 
	int bytes_sent, total_bytes_sent;
	int on = 1;
	unsigned long num_to_read;
	struct timeval timeout;
	struct thread_args *starter_thread_arg;
	WSADATA wsa_data;     
	HANDLE starter_thread_handle;
	DWORD starter_thread_id;
	int client_sockets[NUM_THREADS];
	fd_set socket_fds;
	int size;
	int i;

	total_bytes_received = total_bytes_sent = 0;
	
	if (WSAStartup(MAKEWORD(2, 0), &wsa_data) != 0) {
		fprintf(stderr, "WSAStartup() error");
		exit(1);
	}
	
	total_bytes_received = 0;
	total_bytes_sent = 0;
	
	if ((server_sock = socket(PF_INET, SOCK_STREAM,
				  IPPROTO_TCP)) < 0)
		fatal_error("socket() error");
	
	memset(&client_addr, 0, sizeof(client_addr));     
	memset(&server_addr, 0, sizeof(server_addr));     
	server_addr.sin_family  = AF_INET;       
	server_addr.sin_addr.s_addr = htonl(INADDR_ANY); 
	server_addr.sin_port = htons(SERVER_PORT);
	
	if (bind(server_sock, (struct sockaddr *) &server_addr,
		 sizeof(server_addr)) < 0)
		fatal_error ("bind() error ");
	if (listen(server_sock, 5) < 0)
		fatal_error("listen() error");
	
	if ((starter_thread_arg =
	     (struct thread_args *)
	     malloc(sizeof(struct thread_args))) == 0)
		fatal_error("malloc starter_thread_arg error");

	starter_thread_arg->server_sock = server_sock;
	server_addr.sin_addr.s_addr = inet_addr(SERVER_ADDR);
	memcpy(&starter_thread_arg->server_addr , &server_addr,
	       sizeof(server_addr));
	starter_thread_arg->id = -1;
	
	if ((starter_thread_handle =
	     CreateThread(0,0,
			  (LPTHREAD_START_ROUTINE)starter_thread,
			  starter_thread_arg, 0,
			  (LPDWORD)&starter_thread_id)) == 0)
		fatal_error("CreateThread for starter thread error");
	
	for (i = 0; i < NUM_THREADS; i++) {
		client_addr_len = sizeof(client_addr);
		if ((client_sock = accept(server_sock,
					  (struct sockaddr *) &client_addr,
					  &client_addr_len)) < 0)
			fatal_error("accept() error");
#if 0
		printf("connection accepted from %s\n",
		       inet_ntoa(client_addr.sin_addr));
#endif
		client_sockets[i] = client_sock;
	}
	printf("%d clients accepted\n", NUM_THREADS);

	/* send startup message to all clients */
	for (i = 0; i < NUM_THREADS; i++) {
		int startup_msg_len ;

		client_sock = client_sockets[i];
		memset(buffer, 0, sizeof(buffer));
		strcpy(buffer, "startup");
		startup_msg_len = strlen(buffer);
		if ((bytes_sent =
		     send(client_sock, buffer,
			  startup_msg_len, 0)) != startup_msg_len)
			fatal_error("sending start signal failed");

		size = SERVER_SEND_SOCK_BUFFER_SIZE;
		if (setsockopt(client_sock, SOL_SOCKET, SO_SNDBUF, &size, sizeof(size)) < 0)
			fatal_error("SO_SNDBUF error  ");
		size = SERVER_RECV_SOCK_BUFFER_SIZE;
		if (setsockopt(client_sock, SOL_SOCKET, SO_RCVBUF, &size, sizeof(size)) < 0)
			fatal_error("SO_RCVBUF error ");
	
		if (ioctlsocket(client_sock, FIONBIO, &on) < 0)
			fatal_error("FIONBIO error");
	}

	printf("sent startup messages\n"); fflush(stdout);
	for (;;)  {
		int half = BUFFER_SIZE / 2;

		if (threads_all_done) break;

		Sleep(100);	/* slow down server artificially */
		
		FD_ZERO(&socket_fds);
		for (i = 0; i < NUM_THREADS; i++)
			FD_SET(client_sockets[i], &socket_fds);
		timeout.tv_sec = 0;
		timeout.tv_usec = 10000;

		if (select(0, &socket_fds, 0, 0, &timeout) == 0)
			continue;

		for (i = 0; i < NUM_THREADS; i++) {
			int errno;
			
			if (! FD_ISSET(client_sockets[i], &socket_fds))
				continue;

			client_sock = client_sockets[i];

			/* send half as much */
			if ((bytes_sent =
			     send(client_sock, buffer,
				 half, 0)) != half) {
				errno = WSAGetLastError();
				if (errno == WSAEWOULDBLOCK ||
				    errno == WSAENOBUFS)
					continue;
				fatal_error("send() error");
			}
			total_bytes_sent += bytes_sent;
			
			num_to_read = 0;
			if (ioctlsocket(client_sock, FIONREAD, &num_to_read) < 0) 
				fatal_error("FIONREAD error");
			
			if (num_to_read == 0)
				continue;
			
			/* read half as much */
			num_to_read = num_to_read >= half ? half - 1 : num_to_read;
			if ((bytes_received =
			     recv(client_sock, buffer, num_to_read, 0)) <= 0)
				fatal_error("recv() error ");
			total_bytes_received += bytes_received;
		}
	}
	
	closesocket(server_sock);
	closesocket(client_sock);
	WSACleanup();
	WaitForSingleObject(starter_thread_handle, INFINITE);

	printf("all threads finished. total bytes received %d sent %d\n",
	       total_bytes_received, total_bytes_sent);
	
	exit(0);
}

Discover bluetooth devices around you

Pys60 has good bluetooth support from the beginning.
However, to discover another device, it require you to
interact with the app, choosing a device from the list.
PDIS has a library that help you list all devices silently.
# need to install these 2 modules from PDIS first
import aosocketnativenew
from aosocket.symbian.bt_device_discoverer import *

def callback(error, devices, cb_param=None):
    for address, name in devices:      
        print "Found: ", name, address
# You can get more data by importing socket and try 
# bt_discover(address) or bt_obex_discover(address)
# see details in official pys60 doc on socket module

lister = BtDeviceLister()
lister.discover_all(callback, None)

I summarize the code above from thejamo's example here.
His code is more complete with error checking.
« Newer Snippets
Older Snippets »
Showing 1-10 of 11 total  RSS