Python socket.getprotobyname() Examples

The following are code examples for showing how to use socket.getprotobyname(). They are from open source Python projects. You can vote up the examples you like or vote down the ones you don't like.

Example 1
Project: netmet   Author: godaddy   File: ping.py    Apache License 2.0 6 votes vote down vote up
def _create_socket(self):
        try:
            socket.inet_pton(socket.AF_INET, self.dest)
            dest_ip = self.dest
        except socket.error:
            try:
                dest_ip = socket.gethostbyname(self.dest)
            except socket.gaierror:
                self.ret_code = EXIT_STATUS.ERROR_HOST_NOT_FOUND
                return
        self.dest_ip = dest_ip

        try:
            self.sock = socket.socket(socket.AF_INET, socket.SOCK_RAW,
                                      socket.getprotobyname("icmp"))
        except socket.error as e:
            if e.errno == 1:
                self.ret_code = EXIT_STATUS.ERROR_ROOT_REQUIRED
            else:
                self.ret_code = EXIT_STATUS.ERROR_CANT_OPEN_SOCKET
            return 
Example 2
Project: cqp-sdk-for-py37-native   Author: crud-boy   File: _socket.py    GNU General Public License v2.0 6 votes vote down vote up
def getprotobyname(name):
    """Look up a protocol number by name. (Rarely used.)

    Like :func:`socket.getprotobyname`, but async.

    """
    return await trio.to_thread.run_sync(
        _stdlib_socket.getprotobyname, name, cancellable=True
    )


# obsolete gethostbyname etc. intentionally omitted
# likewise for create_connection (use open_tcp_stream instead)

################################################################
# Socket "constructors"
################################################################ 
Example 3
Project: npmdocker   Author: hongfeioo   File: ping.py    Apache License 2.0 6 votes vote down vote up
def do_one(dest_addr, timeout):
    """
    Returns either the delay (in seconds) or none on timeout.
    """
    icmp = socket.getprotobyname("icmp")
    try:
        my_socket = socket.socket(socket.AF_INET, socket.SOCK_RAW, icmp)
    except socket.error, (errno, msg):
        if errno == 1:
            # Operation not permitted
            msg = msg + (
                " - Note that ICMP messages can only be sent from processes"
                " running as root."
            )
            raise socket.error(msg)
        raise # raise the original error 
Example 4
Project: g3ar   Author: VillanCh   File: ping.py    BSD 2-Clause "Simplified" License 6 votes vote down vote up
def do_one(dest_addr, timeout):
    """
    Returns either the delay (in seconds) or none on timeout.
    """
    icmp = socket.getprotobyname("icmp")
    try:
        my_socket = socket.socket(socket.AF_INET, socket.SOCK_RAW, icmp)
    except socket.error as xxx_todo_changeme:
        (errno, msg) = xxx_todo_changeme.args
        if errno == 1:
            # Operation not permitted
            msg = msg + (
                " - Note that ICMP messages can only be sent from processes"
                " running as root."
            )
            raise socket.error(msg)
        raise # raise the original error

    my_ID = os.getpid() & 0xFFFF

    send_one_ping(my_socket, dest_addr, my_ID)
    delay = receive_one_ping(my_socket, my_ID, timeout)

    my_socket.close()
    return delay 
Example 5
Project: g3ar   Author: VillanCh   File: ping.py    BSD 2-Clause "Simplified" License 6 votes vote down vote up
def do_one(dest_addr, timeout):
    """
    Returns either the delay (in seconds) or none on timeout.
    """
    icmp = socket.getprotobyname("icmp")
    try:
        my_socket = socket.socket(socket.AF_INET, socket.SOCK_RAW, icmp)
    except socket.error as xxx_todo_changeme:
        (errno, msg) = xxx_todo_changeme.args
        if errno == 1:
            # Operation not permitted
            msg = msg + (
                " - Note that ICMP messages can only be sent from processes"
                " running as root."
            )
            raise socket.error(msg)
        raise # raise the original error

    my_ID = os.getpid() & 0xFFFF

    send_one_ping(my_socket, dest_addr, my_ID)
    delay = receive_one_ping(my_socket, my_ID, timeout)

    my_socket.close()
    return delay 
Example 6
Project: traceflow   Author: rucarrol   File: socket_handler.py    BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def __init__(self, ip_daddr):
        # We're only interested in ICMP, so happy to have this hard coded.
        try:
            self.icmp_listener = socket.socket(
                socket.AF_INET, socket.SOCK_RAW, socket.getprotobyname("icmp")
            )
        except PermissionError as e:
            print(e)
            print("Please run as root!")
            exit(1)
        # TODO: Test Timestamps correctly
        try:
            SO_TIMESTAMPNS = 35
            self.icmp_listener.setsockopt(socket.SOL_SOCKET, SO_TIMESTAMPNS, 1)
        except OSError as e:
            logging.debug("Timestamps not available, continuing without them for now")
        self.ip_daddr = ip_daddr
        self.mutex = threading.Lock()
        logging.debug("Starting")
        self.icmp_packets = dict()
        t = threading.Thread(target=self.listener)
        t.setDaemon(True)
        t.start() 
Example 7
Project: linux_network_watchdog   Author: mytechia   File: ping.py    GNU General Public License v3.0 6 votes vote down vote up
def do_one(dest_addr, timeout, psize):
    """
    Returns either the delay (in seconds) or none on timeout.
    """
    icmp = socket.getprotobyname("icmp")
    try:
        my_socket = socket.socket(socket.AF_INET, socket.SOCK_RAW, icmp)
    except socket.error, (errno, msg):
        if errno == 1:
            # Operation not permitted
            msg = msg + (
                " - Note that ICMP messages can only be sent from processes"
                " running as root."
            )
            raise socket.error(msg)
        raise # raise the original error 
Example 8
Project: photonLauncher   Author: sunjerry019   File: ping.py    Apache License 2.0 6 votes vote down vote up
def do_one(dest_addr, timeout):
    """
    Returns either the delay (in seconds) or none on timeout.
    """
    icmp = socket.getprotobyname("icmp")
    try:
        my_socket = socket.socket(socket.AF_INET, socket.SOCK_RAW, icmp)
    except socket.error, (errno, msg):
        if errno == 1:
            # Operation not permitted
            msg = msg + (
                " - Note that ICMP messages can only be sent from processes"
                " running as root."
            )
            raise socket.error(msg)
        raise # raise the original error 
Example 9
Project: gcp_latency   Author: noqcks   File: pyping.py    MIT License 6 votes vote down vote up
def do_one(dest_addr, timeout, psize):
    """
    Returns either the delay (in seconds) or none on timeout.
    """
    icmp = socket.getprotobyname("icmp")
    try:
        my_socket = socket.socket(socket.AF_INET, socket.SOCK_RAW, icmp)
    except socket.error, (errno, msg):
        if errno == 1:
            # Operation not permitted
            msg = msg + (
                " - Note that ICMP messages can only be sent from processes"
                " running as root."
            )
            raise socket.error(msg)
        raise # raise the original error 
Example 10
Project: pythonping   Author: alessandromaggio   File: network.py    MIT License 6 votes vote down vote up
def __init__(self, destination, protocol, source=None, options=()):
        """Creates a network socket to exchange messages

        :param destination: Destination IP address
        :type destination: str
        :param protocol: Name of the protocol to use
        :type protocol: str
        :param options: Options to set on the socket
        :type options: tuple
        :param source: Source IP to use - implemented in future releases
        :type source: Union[None, str]"""
        self.destination = socket.gethostbyname(destination)
        self.protocol = socket.getprotobyname(protocol)
        if source is not None:
            raise NotImplementedError('PythonPing currently does not support specification of source IP')
        self.socket = socket.socket(socket.AF_INET, socket.SOCK_RAW, self.protocol)
        if options:
            self.socket.setsockopt(*options) 
Example 11
Project: Python-Network-Programming-Cookbook-Second-Edition   Author: PacktPublishing   File: 3_2_ping_remote_host.py    MIT License 6 votes vote down vote up
def ping_once(self):
        """
        Returns the delay (in seconds) or none on timeout.
        """
        icmp = socket.getprotobyname("icmp")
        try:
            sock = socket.socket(socket.AF_INET, socket.SOCK_RAW, icmp)
        except socket.error as e:
            if e.errno == 1:
                # Not superuser, so operation not permitted
                e.msg +=  "ICMP messages can only be sent from root user processes"
                raise socket.error(e.msg)
        except Exception as e:
            print ("Exception: %s" %(e))
    
        my_ID = os.getpid() & 0xFFFF
     
        self.send_ping(sock, my_ID)
        delay = self.receive_pong(sock, my_ID, self.timeout)
        sock.close()
        return delay 
Example 12
Project: whatwaff   Author: SVelizDonoso   File: whatwaff.py    MIT License 5 votes vote down vote up
def traceroute(dest_addr, max_hops=30, timeout=0.2):
    print "[*] Verificando Ruta del Servidor :"
    proto_icmp = socket.getprotobyname('icmp')
    proto_udp = socket.getprotobyname('udp')
    port = 33434

    for ttl in xrange(1, max_hops+1):
        rx = socket.socket(socket.AF_INET, socket.SOCK_RAW, proto_icmp)
        rx.settimeout(timeout)
        rx.bind(('', port))
        tx = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, proto_udp)
        tx.setsockopt(socket.SOL_IP, socket.IP_TTL, ttl)
        tx.sendto('', (dest_addr, port))

        try:
            data, curr_addr = rx.recvfrom(512)
            curr_addr = curr_addr[0]
        except socket.error:
            curr_addr = None
        finally:
            rx.close()
            tx.close()

        yield curr_addr

        if curr_addr == dest_addr:
            break 
Example 13
Project: xunfeng   Author: ysrc   File: icmp.py    GNU General Public License v3.0 5 votes vote down vote up
def __icmpSocket(self):
        Sock = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.getprotobyname("icmp"))
        return Sock 
Example 14
Project: icmp-remote-shell   Author: alex-kostirin   File: common.py    MIT License 5 votes vote down vote up
def send_one(dest_addr, delay, payload):
    icmp = socket.getprotobyname("icmp")
    my_socket = socket.socket(socket.AF_INET, socket.SOCK_RAW, icmp)
    my_id = os.getpid() & 0xFFFF
    send_one_ping(my_socket, dest_addr, my_id, payload)
    my_socket.close()
    time.sleep(delay) 
Example 15
Project: automatic-repo   Author: WZQ1397   File: panelPing.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def do_one(dest_addr, timeout):
    icmp = socket.getprotobyname("icmp")
    try:
        my_socket = socket.socket(socket.AF_INET, socket.SOCK_RAW, icmp)
    except socket.error, (errno, msg):
        if errno == 1:
            msg = msg + (
            " - Note that ICMP messages can only be sent from processes"
            " running as root."
          )
            raise socket.error(msg)
        raise # raise the original error 
Example 16
Project: automatic-repo   Author: WZQ1397   File: public.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def do_one(dest_addr, timeout):
    import socket
    icmp = socket.getprotobyname("icmp")
    try:
        my_socket = socket.socket(socket.AF_INET, socket.SOCK_RAW, icmp)
    except socket.error, (errno, msg):
        if errno == 1:
            msg = msg + (
            " - Note that ICMP messages can only be sent from processes"
            " running as root."
          )
            return socket.error(msg)
        return timeout*1000; # raise the original error 
Example 17
Project: useful-scripts   Author: opencoff   File: pingsubnet.py    GNU General Public License v2.0 5 votes vote down vote up
def sockv4():
    """Return an IPv4 socket."""
    # can not create a raw socket if not root or setuid to root
    try:
        sock = socket.socket(socket.AF_INET, socket.SOCK_RAW, \
                                   socket.getprotobyname("icmp"))
    except socket.error, e:
        die("You must be root (%s uses raw sockets)" % os.path.basename(sys.argv[0])) 
Example 18
Project: traceflow   Author: rucarrol   File: packet.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _encode_ipv4_udp_packet(self: object) -> bytes:
        """
        encode_ipv4_udp_packet encodes a valid (IPv4) UDP packet. The IPv4 limitation is due to IPv4 requiring a pseudo header
        where as IPv6 no longer requires src/dst IP address to be used as input to the checksum function.

        :return: udp header, bytes + udp_data, the Payload
        :rtype: bytes
        """
        # Since we cannot determine the ip.id of the packet we send via socket.SOCK_DGRAM, we need to use raw sockets
        # To build a packet manually. This is the only way that I can see where we will know the ip.id in advance
        logging.debug("Encoding UDP Packet now")
        # put the current timestamp into the UDP payload.
        self.data = str(int(time.time())).encode()
        # UDP is a bit stupid, and takes a lower layer info as part of it's checksum. Specifically src/dst IP addr.
        # This is called the pseudo header
        pseudo_header = struct.pack(
            "!BBH", 0, socket.getprotobyname("udp"), len(self.data) + 8
        )
        pseudo_header = self.ip_saddr + self.ip_daddr + pseudo_header
        # Set the checksum to 0, so we can generate a header, then calculate the checksum and re-apply
        checksum = 0
        udp_header = struct.pack(
            "!4H", self.udp_src_port, self.udp_dst_port, len(self.data) + 8, checksum
        )
        checksum = self._checksum_func(pseudo_header + udp_header + self.data)
        udp_header = struct.pack(
            "!4H", self.udp_src_port, self.udp_dst_port, len(self.data) + 8, checksum
        )
        return udp_header + self.data 
Example 19
Project: py-sys   Author: vicky-tan   File: ping_icmp.py    Apache License 2.0 5 votes vote down vote up
def ping_once(self, dest_addr, timeout, sequence):
        icmp = socket.getprotobyname('icmp')
        
        try:
            icmp_socket = socket.socket(socket.AF_INET, socket.SOCK_RAW, icmp)
        except socket.error, (errno, msg):
            if errno == 1:
                msg = '%s : Just root can send ICMP Message' % msg
                raise socket.error(msg)
            raise 
Example 20
Project: dmind   Author: siouka   File: WKS.py    GNU General Public License v2.0 5 votes vote down vote up
def from_text(cls, rdclass, rdtype, tok, origin = None, relativize = True):
        address = tok.get_string()
        protocol = tok.get_string()
        if protocol.isdigit():
            protocol = int(protocol)
        else:
            protocol = socket.getprotobyname(protocol)
        bitmap = []
        while 1:
            token = tok.get().unescape()
            if token.is_eol_or_eof():
                break
            if token.value.isdigit():
                serv = int(token.value)
            else:
                if protocol != _proto_udp and protocol != _proto_tcp:
                    raise NotImplementedError("protocol must be TCP or UDP")
                if protocol == _proto_udp:
                    protocol_text = "udp"
                else:
                    protocol_text = "tcp"
                serv = socket.getservbyname(token.value, protocol_text)
            i = serv // 8
            l = len(bitmap)
            if l < i + 1:
                for j in xrange(l, i + 1):
                    bitmap.append('\x00')
            bitmap[i] = chr(ord(bitmap[i]) | (0x80 >> (serv % 8)))
        bitmap = dns.rdata._truncate_bitmap(bitmap)
        return cls(rdclass, rdtype, address, protocol, bitmap) 
Example 21
Project: F-Scrack   Author: lovesec   File: F-Scrack.py    GNU General Public License v3.0 5 votes vote down vote up
def __icmpSocket(self):
        Sock = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.getprotobyname("icmp"))
        return Sock 
Example 22
Project: MoeChecker_Backend   Author: kasuganosoras   File: backend2.py    GNU General Public License v3.0 5 votes vote down vote up
def raw_socket(dst_addr, imcp_packet):
	rawsocket = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.getprotobyname("icmp"))
	send_request_ping_time = time.time()
	rawsocket.sendto(imcp_packet, (dst_addr, 80))
	return send_request_ping_time, rawsocket, dst_addr 
Example 23
Project: MoeChecker_Backend   Author: kasuganosoras   File: backend.py    GNU General Public License v3.0 5 votes vote down vote up
def raw_socket(dst_addr, imcp_packet):
	rawsocket = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.getprotobyname("icmp"))
	send_request_ping_time = time.time()
	rawsocket.sendto(imcp_packet, (dst_addr, 80))
	return send_request_ping_time, rawsocket, dst_addr 
Example 24
Project: sipticen   Author: mattaereal   File: sipticen.py    MIT License 5 votes vote down vote up
def get_proto_by_name(name):
    """Returns protocol name based on protocol number.
    """
    return str(socket.getprotobyname(name)) 
Example 25
Project: cheapstream   Author: miltador   File: WKS.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def from_text(cls, rdclass, rdtype, tok, origin = None, relativize = True):
        address = tok.get_string()
        protocol = tok.get_string()
        if protocol.isdigit():
            protocol = int(protocol)
        else:
            protocol = socket.getprotobyname(protocol)
        bitmap = []
        while 1:
            token = tok.get().unescape()
            if token.is_eol_or_eof():
                break
            if token.value.isdigit():
                serv = int(token.value)
            else:
                if protocol != _proto_udp and protocol != _proto_tcp:
                    raise NotImplementedError("protocol must be TCP or UDP")
                if protocol == _proto_udp:
                    protocol_text = "udp"
                else:
                    protocol_text = "tcp"
                serv = socket.getservbyname(token.value, protocol_text)
            i = serv // 8
            l = len(bitmap)
            if l < i + 1:
                for j in xrange(l, i + 1):
                    bitmap.append('\x00')
            bitmap[i] = chr(ord(bitmap[i]) | (0x80 >> (serv % 8)))
        bitmap = dns.rdata._truncate_bitmap(bitmap)
        return cls(rdclass, rdtype, address, protocol, bitmap) 
Example 26
Project: xunfeng   Author: caterqiu   File: icmp.py    GNU General Public License v3.0 5 votes vote down vote up
def __icmpSocket(self):
        Sock = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.getprotobyname("icmp"))
        return Sock 
Example 27
Project: script.elementum.burst   Author: elgatito   File: WKS.py    Do What The F*ck You Want To Public License 5 votes vote down vote up
def from_text(cls, rdclass, rdtype, tok, origin=None, relativize=True):
        address = tok.get_string()
        protocol = tok.get_string()
        if protocol.isdigit():
            protocol = int(protocol)
        else:
            protocol = socket.getprotobyname(protocol)
        bitmap = bytearray()
        while 1:
            token = tok.get().unescape()
            if token.is_eol_or_eof():
                break
            if token.value.isdigit():
                serv = int(token.value)
            else:
                if protocol != _proto_udp and protocol != _proto_tcp:
                    raise NotImplementedError("protocol must be TCP or UDP")
                if protocol == _proto_udp:
                    protocol_text = "udp"
                else:
                    protocol_text = "tcp"
                serv = socket.getservbyname(token.value, protocol_text)
            i = serv // 8
            l = len(bitmap)
            if l < i + 1:
                for j in xrange(l, i + 1):
                    bitmap.append(0)
            bitmap[i] = bitmap[i] | (0x80 >> (serv % 8))
        bitmap = dns.rdata._truncate_bitmap(bitmap)
        return cls(rdclass, rdtype, address, protocol, bitmap) 
Example 28
Project: checkweb   Author: SVelizDonoso   File: checkweb.py    MIT License 5 votes vote down vote up
def traceroute(dest_addr, max_hops=30, timeout=0.2):
    print "[*] Verificando Ruta del Servidor :"
    proto_icmp = socket.getprotobyname('icmp')
    proto_udp = socket.getprotobyname('udp')
    port = 33434

    for ttl in xrange(1, max_hops+1):
        rx = socket.socket(socket.AF_INET, socket.SOCK_RAW, proto_icmp)
        rx.settimeout(timeout)
        rx.bind(('', port))
        tx = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, proto_udp)
        tx.setsockopt(socket.SOL_IP, socket.IP_TTL, ttl)
        tx.sendto('', (dest_addr, port))

        try:
            data, curr_addr = rx.recvfrom(512)
            curr_addr = curr_addr[0]
        except socket.error:
            curr_addr = None
        finally:
            rx.close()
            tx.close()

        yield curr_addr

        if curr_addr == dest_addr:
            break 
Example 29
Project: mysplunk_csc   Author: patel-bhavin   File: WKS.py    Apache License 2.0 5 votes vote down vote up
def from_text(cls, rdclass, rdtype, tok, origin = None, relativize = True):
        address = tok.get_string()
        protocol = tok.get_string()
        if protocol.isdigit():
            protocol = int(protocol)
        else:
            protocol = socket.getprotobyname(protocol)
        bitmap = []
        while 1:
            token = tok.get().unescape()
            if token.is_eol_or_eof():
                break
            if token.value.isdigit():
                serv = int(token.value)
            else:
                if protocol != _proto_udp and protocol != _proto_tcp:
                    raise NotImplementedError("protocol must be TCP or UDP")
                if protocol == _proto_udp:
                    protocol_text = "udp"
                else:
                    protocol_text = "tcp"
                serv = socket.getservbyname(token.value, protocol_text)
            i = serv // 8
            l = len(bitmap)
            if l < i + 1:
                for j in xrange(l, i + 1):
                    bitmap.append('\x00')
            bitmap[i] = chr(ord(bitmap[i]) | (0x80 >> (serv % 8)))
        bitmap = dns.rdata._truncate_bitmap(bitmap)
        return cls(rdclass, rdtype, address, protocol, bitmap) 
Example 30
Project: luscan-devel   Author: blackye   File: WKS.py    GNU General Public License v2.0 5 votes vote down vote up
def from_text(cls, rdclass, rdtype, tok, origin = None, relativize = True):
        address = tok.get_string()
        protocol = tok.get_string()
        if protocol.isdigit():
            protocol = int(protocol)
        else:
            protocol = socket.getprotobyname(protocol)
        bitmap = []
        while 1:
            token = tok.get().unescape()
            if token.is_eol_or_eof():
                break
            if token.value.isdigit():
                serv = int(token.value)
            else:
                if protocol != _proto_udp and protocol != _proto_tcp:
                    raise NotImplementedError("protocol must be TCP or UDP")
                if protocol == _proto_udp:
                    protocol_text = "udp"
                else:
                    protocol_text = "tcp"
                serv = socket.getservbyname(token.value, protocol_text)
            i = serv // 8
            l = len(bitmap)
            if l < i + 1:
                for j in xrange(l, i + 1):
                    bitmap.append('\x00')
            bitmap[i] = chr(ord(bitmap[i]) | (0x80 >> (serv % 8)))
        bitmap = dns.rdata._truncate_bitmap(bitmap)
        return cls(rdclass, rdtype, address, protocol, bitmap) 
Example 31
Project: linux-cross-gcc   Author: nmercier   File: WKS.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def from_text(cls, rdclass, rdtype, tok, origin = None, relativize = True):
        address = tok.get_string()
        protocol = tok.get_string()
        if protocol.isdigit():
            protocol = int(protocol)
        else:
            protocol = socket.getprotobyname(protocol)
        bitmap = []
        while 1:
            token = tok.get().unescape()
            if token.is_eol_or_eof():
                break
            if token.value.isdigit():
                serv = int(token.value)
            else:
                if protocol != _proto_udp and protocol != _proto_tcp:
                    raise NotImplementedError("protocol must be TCP or UDP")
                if protocol == _proto_udp:
                    protocol_text = "udp"
                else:
                    protocol_text = "tcp"
                serv = socket.getservbyname(token.value, protocol_text)
            i = serv // 8
            l = len(bitmap)
            if l < i + 1:
                for j in xrange(l, i + 1):
                    bitmap.append('\x00')
            bitmap[i] = chr(ord(bitmap[i]) | (0x80 >> (serv % 8)))
        bitmap = dns.rdata._truncate_bitmap(bitmap)
        return cls(rdclass, rdtype, address, protocol, bitmap) 
Example 32
Project: peach   Author: MozillaSecurity   File: icmp.py    Mozilla Public License 2.0 5 votes vote down vote up
def connect(self):
        if self._socket is not None:
            # Close out old socket first
            self._socket.close()
        self._socket = socket.socket(socket.AF_INET,
                                     socket.SOCK_RAW,
                                     socket.getprotobyname('icmp'))
        self._socket.connect((self._host, 22)) 
Example 33
Project: inwx-zonefile-sync   Author: lukas2511   File: WKS.py    MIT License 5 votes vote down vote up
def from_text(cls, rdclass, rdtype, tok, origin=None, relativize=True):
        address = tok.get_string()
        protocol = tok.get_string()
        if protocol.isdigit():
            protocol = int(protocol)
        else:
            protocol = socket.getprotobyname(protocol)
        bitmap = bytearray()
        while 1:
            token = tok.get().unescape()
            if token.is_eol_or_eof():
                break
            if token.value.isdigit():
                serv = int(token.value)
            else:
                if protocol != _proto_udp and protocol != _proto_tcp:
                    raise NotImplementedError("protocol must be TCP or UDP")
                if protocol == _proto_udp:
                    protocol_text = "udp"
                else:
                    protocol_text = "tcp"
                serv = socket.getservbyname(token.value, protocol_text)
            i = serv // 8
            l = len(bitmap)
            if l < i + 1:
                for j in xrange(l, i + 1):
                    bitmap.append(0)
            bitmap[i] = bitmap[i] | (0x80 >> (serv % 8))
        bitmap = dns.rdata._truncate_bitmap(bitmap)
        return cls(rdclass, rdtype, address, protocol, bitmap) 
Example 34
Project: heartbreaker   Author: lokori   File: config.py    MIT License 5 votes vote down vote up
def parse_args(self):
    (options, args) = OptionParser.parse_args(self)
    try:
      options.proto_num = socket.getprotobyname(options.protocol)
    except socket.error:
      exit("Unsupported protocol " + options.protocol)

    for f in ('bind_address','listen_address','connect_address'):
      setattr(options,f,addrparse(getattr(options,f,None)))

    for f in ('starttime','stoptime'):
      val=getattr(options,f,None)
      try:
        setattr(options,f,float(val))
        continue
      except ValueError:
        pass
      try:
        ts=datetime.datetime.now()
        t=datetime.datetime.strptime(val,'%H:%M:%S')
        ts=ts.replace(hour=t.hour,minute=t.minute,second=t.second)
        setattr(options,f,float(ts.strftime("%Y%m%d%H%M%S")))
      except ValueError:
        exit("Invalid time %s" % val)
      
    return options, args 
Example 35
Project: Cloudmare   Author: MrH0wl   File: WKS.py    GNU General Public License v3.0 5 votes vote down vote up
def from_text(cls, rdclass, rdtype, tok, origin=None, relativize=True):
        address = tok.get_string()
        protocol = tok.get_string()
        if protocol.isdigit():
            protocol = int(protocol)
        else:
            protocol = socket.getprotobyname(protocol)
        bitmap = bytearray()
        while 1:
            token = tok.get().unescape()
            if token.is_eol_or_eof():
                break
            if token.value.isdigit():
                serv = int(token.value)
            else:
                if protocol != _proto_udp and protocol != _proto_tcp:
                    raise NotImplementedError("protocol must be TCP or UDP")
                if protocol == _proto_udp:
                    protocol_text = "udp"
                else:
                    protocol_text = "tcp"
                serv = socket.getservbyname(token.value, protocol_text)
            i = serv // 8
            l = len(bitmap)
            if l < i + 1:
                for j in xrange(l, i + 1):
                    bitmap.append(0)
            bitmap[i] = bitmap[i] | (0x80 >> (serv % 8))
        bitmap = thirdparty.dns.rdata._truncate_bitmap(bitmap)
        return cls(rdclass, rdtype, address, protocol, bitmap) 
Example 36
Project: elasticintel   Author: securityclippy   File: WKS.py    GNU General Public License v3.0 5 votes vote down vote up
def from_text(cls, rdclass, rdtype, tok, origin=None, relativize=True):
        address = tok.get_string()
        protocol = tok.get_string()
        if protocol.isdigit():
            protocol = int(protocol)
        else:
            protocol = socket.getprotobyname(protocol)
        bitmap = bytearray()
        while 1:
            token = tok.get().unescape()
            if token.is_eol_or_eof():
                break
            if token.value.isdigit():
                serv = int(token.value)
            else:
                if protocol != _proto_udp and protocol != _proto_tcp:
                    raise NotImplementedError("protocol must be TCP or UDP")
                if protocol == _proto_udp:
                    protocol_text = "udp"
                else:
                    protocol_text = "tcp"
                serv = socket.getservbyname(token.value, protocol_text)
            i = serv // 8
            l = len(bitmap)
            if l < i + 1:
                for j in xrange(l, i + 1):
                    bitmap.append(0)
            bitmap[i] = bitmap[i] | (0x80 >> (serv % 8))
        bitmap = dns.rdata._truncate_bitmap(bitmap)
        return cls(rdclass, rdtype, address, protocol, bitmap) 
Example 37
Project: 011_python_network_programming_cookbook_demo   Author: jerry-0824   File: 03_02_ping_remote_host.py    MIT License 5 votes vote down vote up
def ping_once(self):
        """
        Returns the delay (in seconds) or none on timeout.
        """
		
        icmp = socket.getprotobyname("icmp")
        try:
            sock = socket.socket(socket.AF_INET, socket.SOCK_RAW, icmp)
        except socket.error, (errno, msg):
            if errno == 1:
                # Not superuser, so operation not permmited
                msg += "ICMP messages can only be sent from root user processes"
                raise socket.error(msg) 
Example 38
Project: Scanver   Author: shad0w008   File: portscan.py    Apache License 2.0 5 votes vote down vote up
def __icmpSocket(self):
        '''创建ICMP Socket'''
        if not self.IPv6:
            Sock = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.getprotobyname("icmp"))
        else:
            Sock = socket.socket(socket.AF_INET6, socket.SOCK_RAW, socket.getprotobyname("ipv6-icmp"))
        return Sock 
Example 39
Project: F-Scrack   Author: y1ng1996   File: F-Scrack.py    GNU General Public License v3.0 5 votes vote down vote up
def __icmpSocket(self):
        Sock = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.getprotobyname("icmp"))
        return Sock 
Example 40
Project: natrixclient   Author: creditease-natrix   File: pyping.py    MIT License 4 votes vote down vote up
def do(self):
        """
        Send one ICMP ECHO_REQUEST and receive the response until self.timeout
        """
        logger.debug("Send one ICMP ECHO_REQUEST and receive the response until self.timeout")
        try:  # One could use UDP here, but it's obscure
            if self.udp:
                current_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.getprotobyname("icmp"))
            else:
                current_socket = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.getprotobyname("icmp"))

            # Bind the socket to a source address
            if self.bind:
                current_socket.bind((self.bind, 0))  # Port number is irrelevant for ICMP
        except socket.error as se:
            logger.exception("socket error")
            if se.errno == 1:
                # Operation not permitted - Add more information to traceback
                etype, evalue, etb = sys.exc_info()
                # evalue = etype("{} - Note that ICMP messages can only be send from processes running as root.".
                #                format(evalue))
                exmsg = "socket error: \ntype: {} \nvalue: {} \ntraceback: {}".format(etype, evalue, etb)
                raise Exception(exmsg)
            raise  # raise the original error
        # except socket.error, (errno, msg):
        #     if errno == 1:
        #         # Operation not permitted - Add more information to traceback
        #         etype, evalue, etb = sys.exc_info()
        #         evalue = etype(
        #             "%s - Note that ICMP messages can only be send from processes running as root." % evalue
        #         )
        #         raise etype, evalue, etb
        #     raise # raise the original error

        send_time = self.send_one_ping(current_socket)
        # if send_time == None:
        if not send_time:
            return
        self.send_count += 1

        receive_time, packet_size, ip, ip_header, icmp_header = self.receive_one_ping(current_socket)
        current_socket.close()

        if receive_time:
            self.receive_count += 1
            delay = (receive_time - send_time) * 1000.0
            self.total_time += delay
            if self.min_time > delay:
                self.min_time = delay
            if self.max_time < delay:
                self.max_time = delay

            self.print_success(delay, ip, packet_size, ip_header, icmp_header)
            return delay
        else:
            self.print_failed() 
Example 41
Project: networks   Author: delimitry   File: icmp.py    MIT License 4 votes vote down vote up
def ping(addr):
    """Send echo request (ping) to addr and get reply"""
    dest = ''
    try:
        dest = socket.gethostbyname(addr)
    except socket.gaierror:
        print('unknown host: {}'.format(addr))
        return

    print('PING {} ({})'.format(addr, dest))
    icmp_header = make_ping_request()

    # prepare payload
    icmp_header_bytes = BytesIO()
    icmp_header_bytes.write(icmp_header)
    icmp_header_bytes.seek(0)

    full_payload = icmp_header_bytes.read()
    print('request: {}'.format(full_payload.hex() if PY3 else full_payload.encode('hex')))

    response = ''
    s = None
    try:
        s = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.getprotobyname('icmp'))
        s.settimeout(1)
        start_time = time.time()
        s.sendto(full_payload, (dest, 0))
        response, _ = s.recvfrom(256)
        end_time = time.time()
    except Exception as ex:
        print(ex)
        return
    finally:
        if s:
            s.close()
    if not response:
        return
    print('response: {}'.format(response.hex() if PY3 else response.encode('hex')))
    print('time = {:.2f} ms'.format((end_time - start_time) * 1000))

    # read IPv4 header
    response_bytes = BytesIO(response)
    ipv4_header = IPv4Header()
    response_bytes.readinto(ipv4_header)

    # read ICMP header
    icmp_echo_header = ICMPEchoHeader()
    response_bytes.readinto(icmp_echo_header)

    print('=====================================================')
    print('IPv4 header')
    print('=====================================================')
    print(ipv4_header)

    print('=====================================================')
    print('ICMP Echo header')
    print('=====================================================')
    print(icmp_echo_header)