tcp snippets

Eventmachine Echo Server Example

Tagged server, eventmachine, echo, tcp  Languages ruby
require 'rubygems'
require 'eventmachine'
require 'logger'

# Each connection creates a new EchoServer.
module EchoServer
  LOG ='echo.log')

  # Called by the event loop immediately after the network connection has been
  # established, and before resumption of the network loop.
  def post_init "-- Connection established #{remote_ip} --"

  # Called by the event loop whenever data has been received by the network
  # connection. It is never called by user code.
  def receive_data data
    message = "#{remote_ip}: #{data}" message
    send_data message
    close_connection if data =~ /quit/i

  # Called by the framework whenever a connection (either a server or client
  # connection) is closed.
  def unbind "-- Connection closed #{remote_ip} --"

  # Return the IP and port of the remote client.
  def remote_ip
    @remote_ip ||= begin
                     port, ip = Socket.unpack_sockaddr_in(get_peername)

EventMachine::run do
  Signal.trap("INT")  { EventMachine.stop }
  Signal.trap("TERM") { EventMachine.stop }
  EventMachine::start_server "", 8080, EchoServer

Use telnet to test it:

$ telnet localhost 8080

How to record and replay TCP traffic

Tagged tcp, replay  Languages bash

First attempt

1) Record TCP traffic with tcpdump to pcap file

Record traffic on ethic from host and port 2332, write to app-traffic.pcap:

tcpdump -vvv -i eth0 host and port 2332 -w app-traffic.pcap &

2) View captured traffic

tcpdump -qns 0 -X -r app-traffic.pcap

Edit captured traffic if needed with Wireshark.

3) Edit source IP so that it’s on your own network

See the ”example in tcprewrite documentation”: for details on how to rewrite source IP:

$ tcprewrite --pnat=, --infile=input.pcap --outfile=output.pcap --skipbroadcast

4) Replay traffic with tcplivereplay from recorded pcap file (note step #3)

”See tcpliveplay documentation”: for details.

Note that tcpliveplay is only available on Linux not OSX.

Second attempt


sudo tcpdump -i en0 host and port 2332 -w app-traffic.pcap


tcpdump -s 0 -n -e -x -vvv -r app-traffic.pcap


sudo tcpreplay -i en0 -t -K app-traffic.pcap

Or use tcplivereplay (Note: Linux only):\#tcpliveplay


I couldn’t get it to work….