當前位置: 首頁>>代碼示例>>Python>>正文


Python socket.getprotobyname方法代碼示例

本文整理匯總了Python中socket.getprotobyname方法的典型用法代碼示例。如果您正苦於以下問題:Python socket.getprotobyname方法的具體用法?Python socket.getprotobyname怎麽用?Python socket.getprotobyname使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在socket的用法示例。


在下文中一共展示了socket.getprotobyname方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: do_one

# 需要導入模塊: import socket [as 別名]
# 或者: from socket import getprotobyname [as 別名]
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 
開發者ID:VillanCh,項目名稱:g3ar,代碼行數:27,代碼來源:ping.py

示例2: __init__

# 需要導入模塊: import socket [as 別名]
# 或者: from socket import getprotobyname [as 別名]
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() 
開發者ID:rucarrol,項目名稱:traceflow,代碼行數:25,代碼來源:socket_handler.py

示例3: do_one_ping

# 需要導入模塊: import socket [as 別名]
# 或者: from socket import getprotobyname [as 別名]
def do_one_ping(self, 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 serr:
            if serr.errno == 1:
                # Operation not permitted
                serr.msg += (
                    " - Note that ICMP messages can only be sent from processes"
                    " running as root."
                )
                raise socket.error(serr.msg)
            raise  # raise the original error
        my_ID = os.getpid() & 0xFFFF
        self.send_one_ping(my_socket, dest_addr, my_ID)
        delay = self.receive_one_ping(my_socket, my_ID, timeout)
        my_socket.close()
        return delay 
開發者ID:PRTG,項目名稱:PythonMiniProbe,代碼行數:23,代碼來源:nmap.py

示例4: __init__

# 需要導入模塊: import socket [as 別名]
# 或者: from socket import getprotobyname [as 別名]
def __init__(self, destination, protocol, source=None, options=(), buffer_size=2048):
        """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]
        :param buffer_size: Size in bytes of the listening buffer for incoming packets (replies)
        :type buffer_size: int"""
        try:
            self.destination = socket.gethostbyname(destination)
        except socket.gaierror as e:
            raise RuntimeError('Cannot resolve address "' + destination + '", try verify your DNS or host file')
        self.protocol = socket.getprotobyname(protocol)
        self.buffer_size = buffer_size
        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) 
開發者ID:alessandromaggio,項目名稱:pythonping,代碼行數:26,代碼來源:network.py

示例5: __init__

# 需要導入模塊: import socket [as 別名]
# 或者: from socket import getprotobyname [as 別名]
def __init__(self, unix_socket_fname = ""):
    Thread.__init__(self)
    self.id = os.getpid()
    if not unix_socket_fname:
        unix_socket_fname = os.path.join(platform.get_dot_dir(),
                                         "xicmp-unix-socket" )
    self.ux_fname = unix_socket_fname
    self.files = {} # id -> IcmpFile
    self.dfs = {}   # id -> deferreds.  A given id may have multiple deferreds.
    #self.sock = socket.socket(socket.AF_INET,socket.SOCK_RAW,
    #                             socket.getprotobyname('icmp'))
    self.sock = open( unix_socket_fname, "rw" )
    os.setuid(os.getuid())      # give up root access as quickly as possible.
    self.sock.settimeout(2.0)   # times out to periodically check done flag.
                                # Separate from time outs on icmp messages.
    #self.lock = Condition()     # simliar to a semaphore, but has only two
    #                            # states: locked and unlocked. 
開發者ID:kenorb-contrib,項目名稱:BitTorrent,代碼行數:19,代碼來源:__init__.py

示例6: ping_once

# 需要導入模塊: import socket [as 別名]
# 或者: from socket import getprotobyname [as 別名]
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 
開發者ID:PacktPublishing,項目名稱:Python-Network-Programming-Cookbook-Second-Edition,代碼行數:23,代碼來源:3_2_ping_remote_host.py

示例7: do_one

# 需要導入模塊: import socket [as 別名]
# 或者: from socket import getprotobyname [as 別名]
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 
開發者ID:hongfeioo,項目名稱:NodePingManage,代碼行數:18,代碼來源:ping.py

示例8: check_name

# 需要導入模塊: import socket [as 別名]
# 或者: from socket import getprotobyname [as 別名]
def check_name(self, name, objtype):
    """ check name validy """

    msg = None
    if len(name) >= 32 or len(re.findall(r'(^_*$|^\d*$|[^a-zA-Z0-9_])', name)) > 0:
        msg = "The {0} name must be less than 32 characters long, may not consist of only numbers, may not consist of only underscores, ".format(objtype)
        msg += "and may only contain the following characters: a-z, A-Z, 0-9, _"
    elif name in ["port", "pass"]:
        msg = "The {0} name must not be either of the reserved words 'port' or 'pass'".format(objtype)
    else:
        try:
            socket.getprotobyname(name)
            msg = 'The {0} name must not be an IP protocol name such as TCP, UDP, ICMP etc.'.format(objtype)
        except socket.error:
            pass

        try:
            socket.getservbyname(name)
            msg = 'The {0} name must not be a well-known or registered TCP or UDP port name such as ssh, smtp, pop3, tftp, http, openvpn etc.'.format(objtype)
        except socket.error:
            pass

    if msg is not None:
        self.module.fail_json(msg=msg) 
開發者ID:opoplawski,項目名稱:ansible-pfsense,代碼行數:26,代碼來源:checks.py

示例9: doOnePing

# 需要導入模塊: import socket [as 別名]
# 或者: from socket import getprotobyname [as 別名]
def doOnePing(destAddr, ID, sequence, timeout):
    icmp = socket.getprotobyname("icmp")

    # SOCK_RAW is a powerful socket type. For more details see: http://sock-raw.org/papers/sock_raw

    # Fill in start
    mySocket = socket.socket(socket.AF_INET, socket.SOCK_RAW, icmp)
    # Fill in end

    sendOnePing(mySocket, ID, sequence, destAddr)
    delay = receiveOnePing(mySocket, ID, sequence, destAddr, timeout)

    mySocket.close()
    return delay 
開發者ID:moranzcw,項目名稱:Computer-Networking-A-Top-Down-Approach-NOTES,代碼行數:16,代碼來源:Ping.py

示例10: __icmpSocket

# 需要導入模塊: import socket [as 別名]
# 或者: from socket import getprotobyname [as 別名]
def __icmpSocket(self):
        Sock = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.getprotobyname("icmp"))
        return Sock 
開發者ID:ysrc,項目名稱:xunfeng,代碼行數:5,代碼來源:icmp.py

示例11: get_valid_protocol

# 需要導入模塊: import socket [as 別名]
# 或者: from socket import getprotobyname [as 別名]
def get_valid_protocol(ip_protocol):
        if isinstance(ip_protocol, str):
            try:
                ip_protocol = socket.getprotobyname(ip_protocol.lower())
            except OSError:
                raise ValueError("Protocol '{}' not found.".format(ip_protocol.lower()))
        elif isinstance(ip_protocol, int):
            if not 0 <= ip_protocol <= 255:
                raise ValueError("Protocol must be between 0 and 255.")
        else:
            raise ValueError("Invalid IP protocol '{}'.".format(ip_protocol))
        return ip_protocol 
開發者ID:Tufin,項目名稱:pytos,代碼行數:14,代碼來源:base_types.py

示例12: _encode_ipv4_udp_packet

# 需要導入模塊: import socket [as 別名]
# 或者: from socket import getprotobyname [as 別名]
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 
開發者ID:rucarrol,項目名稱:traceflow,代碼行數:31,代碼來源:packet.py

示例13: _send_over_socket

# 需要導入模塊: import socket [as 別名]
# 或者: from socket import getprotobyname [as 別名]
def _send_over_socket(self, destination, packet):
        protocol = socket.getprotobyname("icmp")
        if os.geteuid() == 0:
            s = socket.socket(socket.AF_INET, socket.SOCK_RAW, protocol)
        else:
            s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, protocol)
        try:
            s.sendto(packet, (destination, 0))
        except OSError:  # That fixes a mac os bug for me: OSError: [Errno 22] Invalid argument
            pass
        finally:
            s.close() 
開發者ID:rgerganov,項目名稱:py-air-control,代碼行數:14,代碼來源:plain_coap_client.py

示例14: do_one

# 需要導入模塊: import socket [as 別名]
# 或者: from socket import getprotobyname [as 別名]
def do_one(dest_addr, timeout):
    """
    Returns either the delay (in seconds) or none on timeout.
    """
    icmp = socket.getprotobyname("icmp")
    my_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, icmp)

    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 
開發者ID:ywangd,項目名稱:stash,代碼行數:16,代碼來源:ping.py

示例15: from_text

# 需要導入模塊: import socket [as 別名]
# 或者: from socket import getprotobyname [as 別名]
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) 
開發者ID:elgatito,項目名稱:script.elementum.burst,代碼行數:32,代碼來源:WKS.py


注:本文中的socket.getprotobyname方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。