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 = Logger.new('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
    LOG.info "-- Connection established #{remote_ip} --"
  end

  #
  # 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}"
    LOG.info message
    send_data message
    close_connection if data =~ /quit/i
  end

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

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

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

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 196.0.0.1 and port 2332, write to app-traffic.pcap:

tcpdump -vvv -i eth0 host 192.168.0.1 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”:http://tcpreplay.synfin.net/wiki/tcprewrite for details on how to rewrite source IP:

$ tcprewrite --pnat=10.0.0.0/8:172.16.0.0/12,192.168.0.0/16:172.16.0.0/12 --infile=input.pcap --outfile=output.pcap --skipbroadcast

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

”See tcpliveplay documentation”:http://tcpreplay.synfin.net/wiki/tcpliveplay for details.

Note that tcpliveplay is only available on Linux not OSX.

Second attempt

Record:

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


View:

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

Replay:

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

Or use tcplivereplay (Note: Linux only): http://tcpreplay.synfin.net/wiki/tcpliveplay\#tcpliveplay

Result

I couldn’t get it to work….