Skip to content

Commit

Permalink
ADD: use pid to identify pkt with same id from different process
Browse files Browse the repository at this point in the history
  • Loading branch information
noca committed Jun 7, 2018
1 parent 3730b40 commit d2dbed6
Showing 1 changed file with 16 additions and 3 deletions.
19 changes: 16 additions & 3 deletions multiping/__init__.py
Expand Up @@ -17,6 +17,7 @@

__version__ = "1.1.0"

import os
import socket
import struct
import time
Expand All @@ -32,12 +33,14 @@
# Some offsets we use when extracting data from the header
_ICMP_HDR_OFFSET = 20
_ICMP_ID_OFFSET = _ICMP_HDR_OFFSET + 4
_ICMP_IDENT_OFFSET = _ICMP_HDR_OFFSET + 6
_ICMP_PAYLOAD_OFFSET = _ICMP_HDR_OFFSET + 8
_ICMP_ECHO_REQUEST = 8
_ICMP_ECHO_REPLY = 0

_ICMPV6_HDR_OFFSET = 0
_ICMPV6_ID_OFFSET = _ICMPV6_HDR_OFFSET + 4
_ICMPV6_IDENT_OFFSET = _ICMPV6_HDR_OFFSET + 6
_ICMPV6_PAYLOAD_OFFSET = _ICMPV6_HDR_OFFSET + 8
_ICMPV6_ECHO_REQUEST = 128
_ICMPV6_ECHO_REPLY = 129
Expand Down Expand Up @@ -149,6 +152,10 @@ def __init__(self, dest_addrs, sock=None, ignore_lookup_errors=False):
self._receive_has_been_called = False
self._ipv6_address_present = False

# use pid as identifier to filter receive pack from different
# process echo
self.ident = os.getpid() & 0xffff

# Open an ICMP socket, if we weren't provided with one already
if sock:
self._sock = sock
Expand Down Expand Up @@ -226,7 +233,7 @@ def _send_ping(self, dest_addr, payload):
dummy_header = bytearray(
struct.pack(_ICMP_HDR_PACK_FORMAT,
icmp_echo_request, 0, 0,
pkt_id, 0))
pkt_id, self.ident))

# Calculate the checksum over the combined dummy header and payload
checksum = self._checksum(dummy_header + payload)
Expand All @@ -237,7 +244,7 @@ def _send_ping(self, dest_addr, payload):
real_header = bytearray(
struct.pack(_ICMP_HDR_PACK_FORMAT,
icmp_echo_request, 0, checksum,
pkt_id, 0))
pkt_id, self.ident))

# Full packet consists of header plus payload
full_pkt = real_header + payload
Expand Down Expand Up @@ -403,19 +410,25 @@ def receive(self, timeout):

try:
pkt_id = None
pkt_ident = None
if pkt[_ICMPV6_HDR_OFFSET] == _ICMPV6_ECHO_REPLY:

pkt_id = (pkt[_ICMPV6_ID_OFFSET] << 8) + \
pkt[_ICMPV6_ID_OFFSET + 1]
pkt_ident = (pkt[_ICMPV6_IDENT_OFFSET] << 8) + \
pkt[_ICMPV6_IDENT_OFFSET + 1]
payload = pkt[_ICMPV6_PAYLOAD_OFFSET:]

elif pkt[_ICMP_HDR_OFFSET] == _ICMP_ECHO_REPLY:

pkt_id = (pkt[_ICMP_ID_OFFSET] << 8) + \
pkt[_ICMP_ID_OFFSET + 1]
pkt_ident = (pkt[_ICMP_IDENT_OFFSET] << 8) + \
pkt[_ICMP_IDENT_OFFSET + 1]
payload = pkt[_ICMP_PAYLOAD_OFFSET:]

if pkt_id in self._remaining_ids:
if pkt_ident == self.ident and \
pkt_id in self._remaining_ids:
# The sending timestamp was encoded in the echo request
# body and is now returned to us in the response. Note
# that network byte order doesn't matter here, since we
Expand Down

0 comments on commit d2dbed6

Please sign in to comment.