简体   繁体   English

Python 2.7简单数据包嗅探器

[英]Python 2.7 simple packet sniffer

I wrote simple packet sniffer in Python. 我用Python编写了简单的数据包嗅探器。 I need to receive packets non-stop and send one packet every 10 seconds. 我需要不间断地接收数据包,并每10秒发送一个数据包。 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? 有人有更好的主意吗?

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. “当前”永远不能等于自身+10。

Also note that time.time() returns a float value eg: 1440185304.78 还要注意,time.time()返回一个浮点值,例如:1440185304.78

which is very accurate to that exact moment, you should never assume you can find that exact float +10 back. 这对于那个确切的时刻非常准确,您永远不要以为您可以找到那个精确的浮点+10。

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, eg: 在这种情况下,使用较大/较小的语句会更好,因为在循环运行时,可能会传递确切的值,例如:

t = time.time()
while True:
    while time.time() < t + 10:
        time.sleep(0.1)
    t = time.time()
    print ("hi")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM