Python socket.IPPROTO_ICMP Examples

The following are 30 code examples of socket.IPPROTO_ICMP(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module socket , or try the search function .
Example #1
Source File: inet.py    From isip with MIT License 6 votes vote down vote up
def answers(self, other):
        if not isinstance(other,IP):
            return 0
        if conf.checkIPaddr and (self.dst != other.src):
            return 0
        if ( (self.proto == socket.IPPROTO_ICMP) and
             (isinstance(self.payload, ICMP)) and
             (self.payload.type in [3,4,5,11,12]) ):
            # ICMP error message
            return self.payload.payload.answers(other)

        else:
            if ( (conf.checkIPaddr and (self.src != other.dst)) or
                 (self.proto != other.proto) ):
                return 0
            return self.payload.answers(other.payload) 
Example #2
Source File: traffic_pass.py    From fdslight with GNU General Public License v2.0 6 votes vote down vote up
def init_func(self, creator_fd):
        self.__creator_fd = creator_fd
        self.__sent = []

        family = socket.AF_INET

        s = socket.socket(family, socket.SOCK_RAW, socket.IPPROTO_UDP | socket.IPPROTO_ICMP | socket.IPPROTO_UDP | 136)
        s.setsockopt(socket.IPPROTO_IP, socket.IP_HDRINCL, 1)
        s.setblocking(0)

        self.__socket = s
        self.set_fileno(s.fileno())
        self.register(self.fileno)
        self.add_evt_read(self.fileno)

        return self.fileno 
Example #3
Source File: inet.py    From POC-EXP with GNU General Public License v3.0 6 votes vote down vote up
def answers(self, other):
        if not isinstance(other,IP):
            return 0
        if conf.checkIPaddr and (self.dst != other.src):
            return 0
        if ( (self.proto == socket.IPPROTO_ICMP) and
             (isinstance(self.payload, ICMP)) and
             (self.payload.type in [3,4,5,11,12]) ):
            # ICMP error message
            return self.payload.payload.answers(other)

        else:
            if ( (conf.checkIPaddr and (self.src != other.dst)) or
                 (self.proto != other.proto) ):
                return 0
            return self.payload.answers(other.payload) 
Example #4
Source File: __init__.py    From multi-ping with Apache License 2.0 6 votes vote down vote up
def _open_icmp_socket(family):
        """
        Opens a socket suitable for sending/receiving ICMP echo
        requests/responses.

        """
        try:
            proto = socket.IPPROTO_ICMP if family == socket.AF_INET \
                    else _IPPROTO_ICMPV6

            return socket.socket(family, socket.SOCK_RAW, proto)

        except socket.error as e:
            if e.errno == 1:
                raise MultiPingError("Root privileges required for sending "
                                     "ICMP")
            # Re-raise any other error
            raise 
Example #5
Source File: valve_packet.py    From faucet with Apache License 2.0 6 votes vote down vote up
def ipv4_parseable(ip_header_data):
    """Return True if an IPv4 packet we could parse."""
    # TODO: python library parsers are fragile
    # Perform sanity checking on the header to limit exposure of the parser
    ipv4_header = struct.unpack('!BBHHHBBH4s4s', ip_header_data[:IPV4_HEADER_SIZE])
    header_size = (ipv4_header[0] & 0xf) * 32 / 8
    if header_size < IPV4_HEADER_SIZE:
        return False
    flags = ipv4_header[4] >> 12
    # MF bit set
    if flags & 0x2:
        return False
    # fragment - discard
    ip_off = ipv4_header[4] & 0xfff
    if ip_off:
        return False
    # not a protocol conservatively known to parse
    protocol = ipv4_header[6]
    if protocol not in (socket.IPPROTO_ICMP, socket.IPPROTO_UDP, socket.IPPROTO_TCP):
        return False
    return True 
Example #6
Source File: valve_packet.py    From faucet with Apache License 2.0 6 votes vote down vote up
def echo_reply(vid, eth_src, eth_dst, src_ip, dst_ip, data):
    """Return an ICMP echo reply packet.

    Args:
        vid (int or None): VLAN VID to use (or None).
        eth_src (str): Ethernet source address.
        eth_dst (str): destination Ethernet MAC address.
        src_ip (ipaddress.IPv4Address): source IPv4 address.
        dst_ip (ipaddress.IPv4Address): destination IPv4 address.
    Returns:
        ryu.lib.packet.icmp: serialized ICMP echo reply packet.
    """
    pkt = build_pkt_header(vid, eth_src, eth_dst, valve_of.ether.ETH_TYPE_IP)
    ipv4_pkt = ipv4.ipv4(
        dst=dst_ip, src=src_ip, proto=valve_of.inet.IPPROTO_ICMP)
    pkt.add_protocol(ipv4_pkt)
    icmp_pkt = icmp.icmp(
        type_=icmp.ICMP_ECHO_REPLY, code=icmp.ICMP_ECHO_REPLY_CODE,
        data=data)
    pkt.add_protocol(icmp_pkt)
    pkt.serialize()
    return pkt 
Example #7
Source File: inet.py    From mptcp-abuse with GNU General Public License v2.0 6 votes vote down vote up
def answers(self, other):
        if not isinstance(other,IP):
            return 0
        if conf.checkIPaddr and (self.dst != other.src):
            return 0
        if ( (self.proto == socket.IPPROTO_ICMP) and
             (isinstance(self.payload, ICMP)) and
             (self.payload.type in [3,4,5,11,12]) ):
            # ICMP error message
            return self.payload.payload.answers(other)

        else:
            if ( (conf.checkIPaddr and (self.src != other.dst)) or
                 (self.proto != other.proto) ):
                return 0
            return self.payload.answers(other.payload) 
Example #8
Source File: ping3.py    From ping3 with MIT License 6 votes vote down vote up
def ping(dest_addr: str, timeout: int = 4, unit: str = "s", src_addr: str = None, ttl: int = 64, seq: int = 0, size: int = 56, interface: str = None) -> float or None:
    """
    Send one ping to destination address with the given timeout.

    Args:
        dest_addr: The destination address, can be an IP address or a domain name. Ex. "192.168.1.1"/"example.com"
        timeout: Time to wait for a response, in seconds. Default is 4s, same as Windows CMD. (default 4)
        unit: The unit of returned value. "s" for seconds, "ms" for milliseconds. (default "s")
        src_addr: WINDOWS ONLY. The IP address to ping from. This is for multiple network interfaces. Ex. "192.168.1.20". (default None)
        interface: LINUX ONLY. The gateway network interface to ping from. Ex. "wlan0". (default None)
        ttl: The Time-To-Live of the outgoing packet. Default is 64, same as in Linux and macOS. (default 64)
        seq: ICMP packet sequence, usually increases from 0 in the same process. (default 0)
        size: The ICMP packet payload size in bytes. If the input of this is less than the bytes of a double format (usually 8), the size of ICMP packet payload is 8 bytes to hold a time. The max should be the router_MTU(Usually 1480) - IP_Header(20) - ICMP_Header(8). Default is 56, same as in macOS. (default 56)

    Returns:
        The delay in seconds/milliseconds or None on timeout.

    Raises:
        PingError: Any PingError will raise again if `ping3.EXCEPTIONS` is True.
    """
    with socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_ICMP) as sock:
        sock.setsockopt(socket.SOL_IP, socket.IP_TTL, ttl)
        if interface:
            sock.setsockopt(socket.SOL_SOCKET, SOCKET_SO_BINDTODEVICE, interface.encode())  # packets will be sent from specified interface.
            _debug("Socket Interface Binded:", interface)
        if src_addr:
            sock.bind((src_addr, 0))  # only packets send to src_addr are received.
            _debug("Socket Source Address Binded:", src_addr)
        thread_id = threading.get_native_id() if hasattr(threading, 'get_native_id') else threading.currentThread().ident  # threading.get_native_id() is supported >= python3.8.
        process_id = os.getpid()  # If ping() run under different process, thread_id may be identical.
        icmp_id = zlib.crc32("{}{}".format(process_id, thread_id).encode()) & 0xffff  # to avoid icmp_id collision.
        try:
            send_one_ping(sock=sock, dest_addr=dest_addr, icmp_id=icmp_id, seq=seq, size=size)
            delay = receive_one_ping(sock=sock, icmp_id=icmp_id, seq=seq, timeout=timeout)  # in seconds
        except errors.HostUnknown as e:  # Unsolved
            _debug(e)
            _raise(e)
            return False
        except errors.PingError as e:
            _debug(e)
            _raise(e)
            return None
        if delay is None:
            return None
        if unit == "ms":
            delay *= 1000  # in milliseconds
    return delay 
Example #9
Source File: inet.py    From CVE-2016-6366 with MIT License 6 votes vote down vote up
def answers(self, other):
        if not isinstance(other,IP):
            return 0
        if conf.checkIPaddr and (self.dst != other.src):
            return 0
        if ( (self.proto == socket.IPPROTO_ICMP) and
             (isinstance(self.payload, ICMP)) and
             (self.payload.type in [3,4,5,11,12]) ):
            # ICMP error message
            return self.payload.payload.answers(other)

        else:
            if ( (conf.checkIPaddr and (self.src != other.dst)) or
                 (self.proto != other.proto) ):
                return 0
            return self.payload.answers(other.payload) 
Example #10
Source File: inet.py    From smod-1 with GNU General Public License v2.0 6 votes vote down vote up
def answers(self, other):
        if not isinstance(other,IP):
            return 0
        if conf.checkIPaddr and (self.dst != other.src):
            return 0
        if ( (self.proto == socket.IPPROTO_ICMP) and
             (isinstance(self.payload, ICMP)) and
             (self.payload.type in [3,4,5,11,12]) ):
            # ICMP error message
            return self.payload.payload.answers(other)

        else:
            if ( (conf.checkIPaddr and (self.src != other.dst)) or
                 (self.proto != other.proto) ):
                return 0
            return self.payload.answers(other.payload) 
Example #11
Source File: traceroute.py    From FinalRecon with MIT License 6 votes vote down vote up
def tcp_trace(ip, port, tr_tout, output, collect):
	status = {'end': False}
	rx = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_ICMP)
	rx.setblocking(0)
	rx.settimeout(tr_tout)
	rx.bind(('', 0))

	print('\n' + R + 'HOPS'.ljust(7) + 'IP'.ljust(17) + 'HOST' + W + '\n')

	for ttl in range(1,31):
		t = threading.Thread(target=tcp_send(ip, port, ttl, rx, status, tr_tout, output, collect), daemon=True)
		t = t.start()

		if status['end'] == True:
			break
	rx.close() 
Example #12
Source File: inet.py    From kamene with GNU General Public License v2.0 6 votes vote down vote up
def answers(self, other):
        if not isinstance(other, IP):
            return 0
        if conf.checkIPaddr and (self.dst != other.src):
            return 0
        if ((self.proto == socket.IPPROTO_ICMP) and
            (isinstance(self.payload, ICMP)) and
                (self.payload.type in [3, 4, 5, 11, 12])):
            # ICMP error message
            return self.payload.payload.answers(other)

        else:
            if ((conf.checkIPaddr and (self.src != other.dst)) or
                    (self.proto != other.proto)):
                return 0
            return self.payload.answers(other.payload) 
Example #13
Source File: inet.py    From CyberScan with GNU General Public License v3.0 6 votes vote down vote up
def answers(self, other):
        if not isinstance(other,IP):
            return 0
        if conf.checkIPaddr and (self.dst != other.src):
            return 0
        if ( (self.proto == socket.IPPROTO_ICMP) and
             (isinstance(self.payload, ICMP)) and
             (self.payload.type in [3,4,5,11,12]) ):
            # ICMP error message
            return self.payload.payload.answers(other)

        else:
            if ( (conf.checkIPaddr and (self.src != other.dst)) or
                 (self.proto != other.proto) ):
                return 0
            return self.payload.answers(other.payload) 
Example #14
Source File: inet.py    From dash-hack with MIT License 6 votes vote down vote up
def answers(self, other):
        if not isinstance(other,IP):
            return 0
        if conf.checkIPaddr and (self.dst != other.src):
            return 0
        if ( (self.proto == socket.IPPROTO_ICMP) and
             (isinstance(self.payload, ICMP)) and
             (self.payload.type in [3,4,5,11,12]) ):
            # ICMP error message
            return self.payload.payload.answers(other)

        else:
            if ( (conf.checkIPaddr and (self.src != other.dst)) or
                 (self.proto != other.proto) ):
                return 0
            return self.payload.answers(other.payload) 
Example #15
Source File: inet.py    From arissploit with GNU General Public License v3.0 6 votes vote down vote up
def answers(self, other):
        if not isinstance(other,IP):
            return 0
        if conf.checkIPaddr and (self.dst != other.src):
            return 0
        if ( (self.proto == socket.IPPROTO_ICMP) and
             (isinstance(self.payload, ICMP)) and
             (self.payload.type in [3,4,5,11,12]) ):
            # ICMP error message
            return self.payload.payload.answers(other)

        else:
            if ( (conf.checkIPaddr and (self.src != other.dst)) or
                 (self.proto != other.proto) ):
                return 0
            return self.payload.answers(other.payload) 
Example #16
Source File: inet.py    From dash-hack with MIT License 6 votes vote down vote up
def answers(self, other):
        if not isinstance(other,IP):
            return 0
        if conf.checkIPaddr and (self.dst != other.src):
            return 0
        if ( (self.proto == socket.IPPROTO_ICMP) and
             (isinstance(self.payload, ICMP)) and
             (self.payload.type in [3,4,5,11,12]) ):
            # ICMP error message
            return self.payload.payload.answers(other)

        else:
            if ( (conf.checkIPaddr and (self.src != other.dst)) or
                 (self.proto != other.proto) ):
                return 0
            return self.payload.answers(other.payload) 
Example #17
Source File: test_socket.py    From CTFCrackTools-V2 with GNU General Public License v3.0 5 votes vote down vote up
def testBadSockTypeProtoCombination(self):
        for socktype, proto in [
            (socket.SOCK_STREAM, socket.IPPROTO_UDP),
            (socket.SOCK_STREAM, socket.IPPROTO_ICMP),
            (socket.SOCK_DGRAM,  socket.IPPROTO_TCP),
            (socket.SOCK_DGRAM,  socket.IPPROTO_FRAGMENT),
            ]:
            try:
                results = socket.getaddrinfo(HOST, PORT, socket.AF_UNSPEC, socktype, proto)
                self.failUnless(len(results) == 0, "getaddrinfo with bad socktype/proto combo should not have returned results")
            except Exception, x:
                self.fail("getaddrinfo with bad socktype/proto combo should not have raised exception") 
Example #18
Source File: inet.py    From isip with MIT License 5 votes vote down vote up
def hashret(self):
        if ( (self.proto == socket.IPPROTO_ICMP)
             and (isinstance(self.payload, ICMP))
             and (self.payload.type in [3,4,5,11,12]) ):
            return self.payload.payload.hashret()
        else:
            if conf.checkIPsrc and conf.checkIPaddr:
                return strxor(inet_aton(self.src),inet_aton(self.dst))+struct.pack("B",self.proto)+self.payload.hashret()
            else:
                return struct.pack("B", self.proto)+self.payload.hashret() 
Example #19
Source File: inet.py    From POC-EXP with GNU General Public License v3.0 5 votes vote down vote up
def hashret(self):
        if ( (self.proto == socket.IPPROTO_ICMP)
             and (isinstance(self.payload, ICMP))
             and (self.payload.type in [3,4,5,11,12]) ):
            return self.payload.payload.hashret()
        else:
            if conf.checkIPsrc and conf.checkIPaddr:
                return strxor(inet_aton(self.src),inet_aton(self.dst))+struct.pack("B",self.proto)+self.payload.hashret()
            else:
                return struct.pack("B", self.proto)+self.payload.hashret() 
Example #20
Source File: inet.py    From dash-hack with MIT License 5 votes vote down vote up
def hashret(self):
        if ( (self.proto == socket.IPPROTO_ICMP)
             and (isinstance(self.payload, ICMP))
             and (self.payload.type in [3,4,5,11,12]) ):
            return self.payload.payload.hashret()
        else:
            if conf.checkIPsrc and conf.checkIPaddr:
                return strxor(inet_aton(self.src),inet_aton(self.dst))+struct.pack("B",self.proto)+self.payload.hashret()
            else:
                return struct.pack("B", self.proto)+self.payload.hashret() 
Example #21
Source File: icmp.py    From tensor with MIT License 5 votes vote down vote up
def createInternetSocket(self):
        s = socket.socket(
            socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_ICMP)

        s.setblocking(0)

        fd = s.fileno()

        # Set close-on-exec

        flags = fcntl.fcntl(fd, fcntl.F_GETFD)
        flags = flags | fcntl.FD_CLOEXEC
        fcntl.fcntl(fd, fcntl.F_SETFD, flags)

        return s 
Example #22
Source File: test_socket.py    From CTFCrackTools-V2 with GNU General Public License v3.0 5 votes vote down vote up
def testNoSockTypeWithProto(self):
        for expect_results, proto in [
            (True,  socket.IPPROTO_UDP),
            (False, socket.IPPROTO_ICMP),
            (True,  socket.IPPROTO_TCP),
            (False, socket.IPPROTO_FRAGMENT),
            ]:
            try:
                results = socket.getaddrinfo(HOST, PORT, socket.AF_UNSPEC, 0, proto)
                if expect_results:
                    self.failUnless(len(results) > 0, "getaddrinfo with no socktype and supported proto combo should have returned results")
                else:
                    self.failUnless(len(results) == 0, "getaddrinfo with no socktype and unsupported proto combo should not have returned results")
            except Exception, x:
                self.fail("getaddrinfo with no socktype (un)supported proto combo should not have raised exception") 
Example #23
Source File: inet.py    From kamene with GNU General Public License v2.0 5 votes vote down vote up
def hashret(self):
        if ((self.proto == socket.IPPROTO_ICMP)
            and (isinstance(self.payload, ICMP))
                and (self.payload.type in [3, 4, 5, 11, 12])):
            return self.payload.payload.hashret()
        else:
            if conf.checkIPsrc and conf.checkIPaddr:
                return strxor(inet_aton(self.src), inet_aton(self.dst)) + struct.pack("B", self.proto) + self.payload.hashret()
            else:
                return struct.pack("B", self.proto) + self.payload.hashret() 
Example #24
Source File: inet.py    From arissploit with GNU General Public License v3.0 5 votes vote down vote up
def hashret(self):
        if ( (self.proto == socket.IPPROTO_ICMP)
             and (isinstance(self.payload, ICMP))
             and (self.payload.type in [3,4,5,11,12]) ):
            return self.payload.payload.hashret()
        else:
            if conf.checkIPsrc and conf.checkIPaddr:
                return strxor(inet_aton(self.src),inet_aton(self.dst))+struct.pack("B",self.proto)+self.payload.hashret()
            else:
                return struct.pack("B", self.proto)+self.payload.hashret() 
Example #25
Source File: test_socket.py    From CTFCrackTools with GNU General Public License v3.0 5 votes vote down vote up
def testBadSockTypeProtoCombination(self):
        for socktype, proto in [
            (socket.SOCK_STREAM, socket.IPPROTO_UDP),
            (socket.SOCK_STREAM, socket.IPPROTO_ICMP),
            (socket.SOCK_DGRAM,  socket.IPPROTO_TCP),
            (socket.SOCK_DGRAM,  socket.IPPROTO_FRAGMENT),
            ]:
            try:
                results = socket.getaddrinfo(HOST, PORT, socket.AF_UNSPEC, socktype, proto)
                self.failUnless(len(results) == 0, "getaddrinfo with bad socktype/proto combo should not have returned results")
            except Exception, x:
                self.fail("getaddrinfo with bad socktype/proto combo should not have raised exception") 
Example #26
Source File: test_socket.py    From CTFCrackTools with GNU General Public License v3.0 5 votes vote down vote up
def testNoSockTypeWithProto(self):
        for expect_results, proto in [
            (True,  socket.IPPROTO_UDP),
            (False, socket.IPPROTO_ICMP),
            (True,  socket.IPPROTO_TCP),
            (False, socket.IPPROTO_FRAGMENT),
            ]:
            try:
                results = socket.getaddrinfo(HOST, PORT, socket.AF_UNSPEC, 0, proto)
                if expect_results:
                    self.failUnless(len(results) > 0, "getaddrinfo with no socktype and supported proto combo should have returned results")
                else:
                    self.failUnless(len(results) == 0, "getaddrinfo with no socktype and unsupported proto combo should not have returned results")
            except Exception, x:
                self.fail("getaddrinfo with no socktype (un)supported proto combo should not have raised exception") 
Example #27
Source File: inet.py    From dash-hack with MIT License 5 votes vote down vote up
def hashret(self):
        if ( (self.proto == socket.IPPROTO_ICMP)
             and (isinstance(self.payload, ICMP))
             and (self.payload.type in [3,4,5,11,12]) ):
            return self.payload.payload.hashret()
        else:
            if conf.checkIPsrc and conf.checkIPaddr:
                return strxor(inet_aton(self.src),inet_aton(self.dst))+struct.pack("B",self.proto)+self.payload.hashret()
            else:
                return struct.pack("B", self.proto)+self.payload.hashret() 
Example #28
Source File: inet.py    From dash-hack with MIT License 5 votes vote down vote up
def hashret(self):
        if ( (self.proto == socket.IPPROTO_ICMP)
             and (isinstance(self.payload, ICMP))
             and (self.payload.type in [3,4,5,11,12]) ):
            return self.payload.payload.hashret()
        else:
            if conf.checkIPsrc and conf.checkIPaddr:
                return strxor(inet_aton(self.src),inet_aton(self.dst))+struct.pack("B",self.proto)+self.payload.hashret()
            else:
                return struct.pack("B", self.proto)+self.payload.hashret() 
Example #29
Source File: host-scanner-via-udp.py    From Offensive-Security-Certified-Professional with MIT License 5 votes vote down vote up
def main(argv):
    global BIND

    if len(argv) < 3:
        print('Usage: ./udp-scan.py <bind-ip> <target-subnet>')
        sys.exit(1)

    bindAddr = sys.argv[1]
    subnet = sys.argv[2]

    sockProto = None
    if os.name == 'nt':
        sockProto = socket.IPPROTO_IP
    else:
        sockProto = socket.IPPROTO_ICMP

    sniffer = socket.socket(socket.AF_INET, socket.SOCK_RAW, sockProto)
    if DEBUG: print('[.] Binding on {}:0'.format(bindAddr))
    sniffer.bind((bindAddr, 0))

    # Include IP headers in the capture
    sniffer.setsockopt(socket.IPPROTO_IP, socket.IP_HDRINCL, 1)

    # In Windows, set up promiscous mode.
    if os.name == 'nt':
        try:
            sniffer.ioctl(socket.SIO_RCVALL, socket.RCVALL_ON)
        except socket.error, e:
            print('[!] Could not set promiscous mode ON: "{}"'.format(str(e)))

    # Sending thread 
Example #30
Source File: ICMP.py    From XFLTReaT with MIT License 5 votes vote down vote up
def serve(self):
		server_socket = None
		self.serverorclient = 1

		try:
			common.internal_print("Starting module: {0} on {1}".format(self.get_module_name(), self.config.get("Global", "serverbind")))
		
			server_socket = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_ICMP)
			if (self.os_type == common.OS_WINDOWS) or (self.os_type == common.OS_MACOSX):
				common.internal_print("This module can be run in client mode only on this operating system.", -1)

				self.cleanup()
				return

			self.comms_socket = server_socket
			self.authenticated = False

			self.communication_initialization()
			self.communication(False) 
			
		except KeyboardInterrupt:

				self.cleanup()
				return

		self.cleanup()

		return