import socket
import time
import fcntl
import random
import struct

from zope.interface import implements

from twisted.internet import task, defer, reactor, udp
from twisted.internet.protocol import DatagramProtocol
from twisted.internet.interfaces import ISystemHandle

# OMG SHUT UP
class STFU(object):
    msg = lambda x, y: None
udp.log = STFU()

class IP(object):
    """IP header decoder
    """
    def __init__(self, packet):
        self.readPacket(packet)

    def readPacket(self, packet):
        vl = struct.unpack('!b', packet[0])[0]
        l = (vl & 0xf) * 4

        head = packet[:l]
        self.offset = struct.unpack('!H', packet[6:8])

        self.payload = packet[l:]

class EchoPacket(object):
    """ICMP Echo packet encoder and decoder
    """
    def __init__(self, seq=0, id=None, data=None, packet=None):
        if packet:
            self.decodePacket(packet)
            self.packet = packet
        else:
            self.id = id
            self.seq = seq
            self.data = data
            self.encodePacket()

    def calculateChecksum(self, buffer):
        nleft = len(buffer)
        sum = 0
        pos = 0
        while nleft > 1:
            sum = ord(buffer[pos]) * 256 + (ord(buffer[pos + 1]) + sum)
            pos = pos + 2
            nleft = nleft - 2