本文整理汇总了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
示例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()
示例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
示例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)
示例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.
示例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
示例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)
示例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
示例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
示例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
示例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
示例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()
示例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
示例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)