本文整理汇总了Python中socket._socketobject方法的典型用法代码示例。如果您正苦于以下问题:Python socket._socketobject方法的具体用法?Python socket._socketobject怎么用?Python socket._socketobject使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类socket
的用法示例。
在下文中一共展示了socket._socketobject方法的14个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_close
# 需要导入模块: import socket [as 别名]
# 或者: from socket import _socketobject [as 别名]
def test_close(self):
import httplib
# calling .close() on urllib2's response objects should close the
# underlying socket
# delve deep into response to fetch socket._socketobject
response = _urlopen_with_retry(test_support.TEST_HTTP_URL)
abused_fileobject = response.fp
self.assertIs(abused_fileobject.__class__, socket._fileobject)
httpresponse = abused_fileobject._sock
self.assertIs(httpresponse.__class__, httplib.HTTPResponse)
fileobject = httpresponse.fp
self.assertIs(fileobject.__class__, socket._fileobject)
self.assertTrue(not fileobject.closed)
response.close()
self.assertTrue(fileobject.closed)
示例2: test_close
# 需要导入模块: import socket [as 别名]
# 或者: from socket import _socketobject [as 别名]
def test_close(self):
import httplib
# calling .close() on urllib2's response objects should close the
# underlying socket
# delve deep into response to fetch socket._socketobject
response = _urlopen_with_retry("http://www.python.org/")
abused_fileobject = response.fp
self.assertTrue(abused_fileobject.__class__ is socket._fileobject)
httpresponse = abused_fileobject._sock
self.assertTrue(httpresponse.__class__ is httplib.HTTPResponse)
fileobject = httpresponse.fp
self.assertTrue(fileobject.__class__ is socket._fileobject)
self.assertTrue(not fileobject.closed)
response.close()
self.assertTrue(fileobject.closed)
示例3: test_close
# 需要导入模块: import socket [as 别名]
# 或者: from socket import _socketobject [as 别名]
def test_close(self):
import httplib
# calling .close() on urllib2's response objects should close the
# underlying socket
# delve deep into response to fetch socket._socketobject
response = _urlopen_with_retry("http://www.example.com/")
abused_fileobject = response.fp
self.assertIs(abused_fileobject.__class__, socket._fileobject)
httpresponse = abused_fileobject._sock
self.assertIs(httpresponse.__class__, httplib.HTTPResponse)
fileobject = httpresponse.fp
self.assertIs(fileobject.__class__, socket._fileobject)
self.assertTrue(not fileobject.closed)
response.close()
self.assertTrue(fileobject.closed)
示例4: _finishInit
# 需要导入模块: import socket [as 别名]
# 或者: from socket import _socketobject [as 别名]
def _finishInit(self, whenDone, skt, error, reactor):
"""
Called by subclasses to continue to the stage of initialization where
the socket connect attempt is made.
@param whenDone: A 0-argument callable to invoke once the connection is
set up. This is L{None} if the connection could not be prepared
due to a previous error.
@param skt: The socket object to use to perform the connection.
@type skt: C{socket._socketobject}
@param error: The error to fail the connection with.
@param reactor: The reactor to use for this client.
@type reactor: L{twisted.internet.interfaces.IReactorTime}
"""
if whenDone:
self._commonConnection.__init__(self, skt, None, reactor)
reactor.callLater(0, whenDone)
else:
reactor.callLater(0, self.failIfNotConnected, error)
示例5: __init__
# 需要导入模块: import socket [as 别名]
# 或者: from socket import _socketobject [as 别名]
def __init__(
self, connection, name=None, queue=None, in_seqno=1, out_seqno=1
):
"""
Create a new ConnectionDetails. Only the connection is required
initially, as the rest of the details are set later.
:param connection: The connection
:type connection: ``socket._socketobject``
:param name: Name of connection (tuple of sender and target)
:type name: ``tuple`` of ``str`` and ``str``
:param queue: Queue of receiving messages
:type queue: ``queue``
:param in_seqno: Input messages sequence number
:type in_seqno: ``int``
:param out_seqno: Output messages sequence number
:type out_seqno: ``int``
"""
self.connection = connection
self.name = name
self.queue = queue
self.in_seqno = in_seqno
self.out_seqno = out_seqno
示例6: _handle_conn
# 需要导入模块: import socket [as 别名]
# 或者: from socket import _socketobject [as 别名]
def _handle_conn(self, conn):
"""
:type conn: socket._socketobject
"""
buf = ""
while True:
data = conn.recv(1024)
log.debug("Recv: %s", data.strip())
if not data:
break
buf += data
if "\n" in buf:
line = buf[:buf.index("\n")]
buf = buf[buf.index("\n") + 1:]
if line:
log.debug("Cmd line: %s", line)
try:
self._handle_cmd(json.loads(line))
except KeyboardInterrupt:
raise
except BaseException:
log.error("Failed to handle cmd: %s", traceback.format_exc())
示例7: test_close
# 需要导入模块: import socket [as 别名]
# 或者: from socket import _socketobject [as 别名]
def test_close(self):
import socket, httplib, gc
# calling .close() on urllib2's response objects should close the
# underlying socket
# delve deep into response to fetch socket._socketobject
response = urllib2.urlopen("http://www.python.org/")
abused_fileobject = response.fp
self.assert_(abused_fileobject.__class__ is socket._fileobject)
httpresponse = abused_fileobject._sock
self.assert_(httpresponse.__class__ is httplib.HTTPResponse)
fileobject = httpresponse.fp
self.assert_(fileobject.__class__ is socket._fileobject)
self.assert_(not fileobject.closed)
response.close()
self.assert_(fileobject.closed)
示例8: fake_socket
# 需要导入模块: import socket [as 别名]
# 或者: from socket import _socketobject [as 别名]
def fake_socket(tmpdir_factory, request):
packets = request.node.callspec.params.get('packets')
# write data to the "socket"; this must be an actual file, because
# select.select()() expects a real file descriptor
filename = str(tmpdir_factory.mktemp('fake-socket').join(str(uuid4())))
f = open(filename, 'w')
request.addfinalizer(f.close)
sockobj = socket._socket.socket if six.PY3 else socket._socketobject
class fakesocket(sockobj):
buff = six.BytesIO()
def _send(self, data):
self.buff.write(data)
return len(data) # number of bytes sent
sock = fakesocket()
sock.f = six.BytesIO(packets)
# socket.socket overrides these at instantiation time to the underlying
# C implementation; set them here so that we can mock send() and recv()
# calls
sock.send = types.MethodType(_send, sock)
sock.recv = types.MethodType(
lambda self, _bytes: self.f.read(_bytes),
sock
)
sock.fileno = types.MethodType(lambda self: f.fileno(), sock)
return sock
示例9: capture
# 需要导入模块: import socket [as 别名]
# 或者: from socket import _socketobject [as 别名]
def capture(self, sock):
""" Capture packets in traffic
param: sock(socket._socketobject): raw socket that listen for traffic
"""
while True:
# socket.recvfrom() method returns tuple object
packet_tuple = sock.recvfrom(65565)
packet_str = packet_tuple[0]
self.packet_parser.parse(self.ip, packet_str)
示例10: _GetSocket
# 需要导入模块: import socket [as 别名]
# 或者: from socket import _socketobject [as 别名]
def _GetSocket(self):
"""Establishes a connection to an nsrlsvr instance.
Returns:
socket._socketobject: socket connected to an nsrlsvr instance or None if
a connection cannot be established.
"""
try:
return socket.create_connection(
(self._host, self._port), self._SOCKET_TIMEOUT)
except socket.error as exception:
logger.error(
'Unable to connect to nsrlsvr with error: {0!s}.'.format(exception))
示例11: _QueryHash
# 需要导入模块: import socket [as 别名]
# 或者: from socket import _socketobject [as 别名]
def _QueryHash(self, nsrl_socket, digest):
"""Queries nsrlsvr for a specific hash.
Args:
nsrl_socket (socket._socketobject): socket of connection to nsrlsvr.
digest (str): hash to look up.
Returns:
bool: True if the hash was found, False if not or None on error.
"""
try:
query = 'QUERY {0:s}\n'.format(digest).encode('ascii')
except UnicodeDecodeError:
logger.error('Unable to encode digest: {0!s} to ASCII.'.format(digest))
return False
response = None
try:
nsrl_socket.sendall(query)
response = nsrl_socket.recv(self._RECEIVE_BUFFER_SIZE)
except socket.error as exception:
logger.error('Unable to query nsrlsvr with error: {0!s}.'.format(
exception))
if not response:
return False
# Strip end-of-line characters since they can differ per platform on which
# nsrlsvr is running.
response = response.strip()
# nsrlsvr returns "OK 1" if the has was found or "OK 0" if not.
return response == b'OK 1'
示例12: send_socket
# 需要导入模块: import socket [as 别名]
# 或者: from socket import _socketobject [as 别名]
def send_socket(socket, sobject):
"""This function sends a filedescriptor.
socket: must be a unix socket
fd: must be a socket of a socket object
Returns True on success, False otherwise
"""
if not isinstance(sobject, _socketobject):
raise TypeError("'sobject' must either be a file or a socket object")
iov = IOVec()
iov.iov_base = "A"
iov.iov_len = 1
cmsg = CMSG()
cmsg.cmsg_hdr.cmsg_len = CMSG_LEN(sizeof(c_int))
cmsg.cmsg_hdr.cmsg_level = SOL_SOCKET
cmsg.cmsg_hdr.cmsg_type = SCM_RIGHTS
pack_into("i", cmsg.cmsg_data, 0, sobject.fileno())
msgh = MSGHdr()
msgh.msg_name = None
msgh.msg_namelen = 0
msgh.msg_iov = (iov,)
msgh.msg_iovlen = 1
msgh.msg_control = pointer(cmsg)
msgh.msg_controllen = CMSG_SPACE(sizeof(c_int))
msgh.msg_flags = 0
rc = sendmsg(socket.fileno(), pointer(msgh), 0)
if rc == -1:
errno = get_errno()
raise OSError(errno, strerror(errno))
return True
示例13: __init__
# 需要导入模块: import socket [as 别名]
# 或者: from socket import _socketobject [as 别名]
def __init__(self, server, sock, makefile=MakeFile):
"""Initialize HTTPConnection instance.
Args:
server (HTTPServer): web server object receiving this request
sock (socket._socketobject): the raw socket object (usually
TCP) for this connection
makefile (file): a fileobject class for reading from the socket
"""
self.server = server
self.socket = sock
self.rfile = makefile(sock, 'rb', self.rbufsize)
self.wfile = makefile(sock, 'wb', self.wbufsize)
self.requests_seen = 0
self.peercreds_enabled = self.server.peercreds_enabled
self.peercreds_resolve_enabled = self.server.peercreds_resolve_enabled
# LRU cached methods:
# Ref: https://stackoverflow.com/a/14946506/595220
self.resolve_peer_creds = (
lru_cache(maxsize=1)(self.resolve_peer_creds)
)
self.get_peer_creds = (
lru_cache(maxsize=1)(self.get_peer_creds)
)
示例14: from_file
# 需要导入模块: import socket [as 别名]
# 或者: from socket import _socketobject [as 别名]
def from_file(input_file, logger=None):
"""This static method acts as a constructor and returns an input
packet with the proper class, based on the packet headers.
The "input_file" parameter must either be a file or a sockect object.
"""
if isinstance(input_file, _socketobject):
def read_file(count):
return input_file.recv(count, MSG_WAITALL)
elif hasattr(file, "read") and callable(file.read):
def read_file(count):
return input_file.read(count)
else:
raise ValueError("'input_file' must either be a socket object or"
" provide a 'read' method")
fields = ("rpc_vers", "rpc_vers_minor", "ptype", "pfc_flags", "drep",
"frag_length", "auth_length", "call_id")
header_data = read_file(16)
# len_header_data = len(header_data)
# if len_header_data < 16:
# raise RTSParsingException("read only %d header bytes from input"
# % len_header_data)
# TODO: value validation
values = unpack_from("<bbbblhhl", header_data)
if values[2] == DCERPC_PKT_FAULT:
packet_class = RPCFaultPacket
elif values[2] == DCERPC_PKT_BIND_ACK:
packet_class = RPCBindACKPacket
elif values[2] == DCERPC_PKT_BIND_NAK:
packet_class = RPCBindNAKPacket
elif values[2] == DCERPC_PKT_RTS:
packet_class = RPCRTSPacket
else:
packet_class = RPCPacket
body_data = read_file(values[5] - 16)
# len_body_data = len(body_data)
# if len_body_data < (values[5] - 16):
# raise RTSParsingException("read only %d body bytes from input"
# % len_body_data)
packet = packet_class(header_data + body_data, logger)
packet.header = dict(zip(fields, values))
packet.offset = 16
packet.size = values[5]
packet.parse()
return packet