0

I wrote simple packet sniffer in Python. I need to receive packets non-stop and send one packet every 10 seconds. I tried this:

current = time.time()
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(("xx.xx.xx.xx",xxxx))

time.sleep(0.5)

while True:
    msg = str(s.recv(4096))
    time.sleep(0.010)
    print msg
    if current==current+10:
        s.send("<myPacket/>")
    current = time.time()

but it doesn't work good. Anyone have better idea?

Tkininter
  • 65
  • 1
  • 9
  • 1
    What do you mean by `but it doesn't work good`? How does it differ from what you expect? You have to be more specific. – That1Guy Aug 21 '15 at 16:42
  • Doesn't look like a sniffer to me... A sniffer, by definition, would read packets of *others*. Not packets directed to it in the first place. – Bakuriu Aug 21 '15 at 16:45

1 Answers1

1

Your time handling is bad, use this instead:

While True:
    ...
    time.sleep(10)

Your code doesn't work because:

'current' can never be equal to itself+10.

Also note that time.time() returns a float value e.g: 1440185304.78

which is very accurate to that exact moment, you should never assume you can find that exact float +10 back.

Using a larger/smaller statement is better in this case since the exact value might have passed while your loop is running whatever is in it, e.g:

t = time.time()
while True:
    while time.time() < t + 10:
        time.sleep(0.1)
    t = time.time()
    print ("hi")
Ayy
  • 478
  • 3
  • 11