Python socket.fromfd() Examples
The following are 30
code examples of socket.fromfd().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
socket
, or try the search function
.
Example #1
Source File: _test_multiprocessing.py From Project-New-Reign---Nemesis-Main with GNU General Public License v3.0 | 6 votes |
def get_high_socket_fd(self): if WIN32: # The child process will not have any socket handles, so # calling socket.fromfd() should produce WSAENOTSOCK even # if there is a handle of the same number. return socket.socket().detach() else: # We want to produce a socket with an fd high enough that a # freshly created child process will not have any fds as high. fd = socket.socket().detach() to_close = [] while fd < 50: to_close.append(fd) fd = os.dup(fd) for x in to_close: os.close(x) return fd
Example #2
Source File: http.py From plex-for-kodi with GNU General Public License v2.0 | 6 votes |
def killSocket(self): if not self.currentResponse: return try: socket.fromfd(self.currentResponse.raw.fileno(), socket.AF_INET, socket.SOCK_STREAM).shutdown(socket.SHUT_RDWR) return except AttributeError: pass except Exception as e: util.ERROR(err=e) try: self.currentResponse.raw._fp.fp._sock.shutdown(socket.SHUT_RDWR) except AttributeError: pass except Exception as e: util.ERROR(err=e)
Example #3
Source File: pullpipe.py From Safejumper-for-Desktop with GNU General Public License v2.0 | 6 votes |
def recvfd(socketfd): """ Receive a file descriptor from a L{sendmsg} message on the given C{AF_UNIX} socket. @param socketfd: An C{AF_UNIX} socket, attached to another process waiting to send sockets via the ancillary data mechanism in L{send1msg}. @param fd: C{int} @return: a 2-tuple of (new file descriptor, description). @rtype: 2-tuple of (C{int}, C{bytes}) """ ourSocket = socket.fromfd(socketfd, socket.AF_UNIX, socket.SOCK_STREAM) data, ancillary, flags = recvmsg(ourSocket) [(cmsgLevel, cmsgType, packedFD)] = ancillary # cmsgLevel and cmsgType really need to be SOL_SOCKET / SCM_RIGHTS, but # since those are the *only* standard values, there's not much point in # checking. [unpackedFD] = unpack("i", packedFD) return (unpackedFD, data)
Example #4
Source File: handleBackendGatewayConnection.py From ufora with Apache License 2.0 | 6 votes |
def __init__(self, socketFd, sharedStateAddress): self.socketFd = socketFd self.callbackSchedulerFactory = CallbackScheduler.createSimpleCallbackSchedulerFactory() self.scheduler = self.callbackSchedulerFactory.createScheduler( "BackendGatewayRequestHandler", 1 ) sharedStateHost, sharedStatePort = sharedStateAddress.split(':') sharedStateViewFactory = ViewFactory.ViewFactory.TcpViewFactory( self.callbackSchedulerFactory.createScheduler('SharedState', 1), sharedStateHost, int(sharedStatePort) ) self.subscribableHandler = ConnectionHandler.ConnectionHandler( self.scheduler, sharedStateViewFactory, lambda: TcpChannelFactory.TcpStringChannelFactory(self.scheduler) ) self.sock = socket.fromfd(socketFd, socket.AF_INET, socket.SOCK_STREAM)
Example #5
Source File: tcp.py From Safejumper-for-Desktop with GNU General Public License v2.0 | 6 votes |
def _fromListeningDescriptor(cls, reactor, fd, addressFamily, factory): """ Create a new L{Port} based on an existing listening I{SOCK_STREAM} socket. Arguments are the same as to L{Port.__init__}, except where noted. @param fd: An integer file descriptor associated with a listening socket. The socket must be in non-blocking mode. Any additional attributes desired, such as I{FD_CLOEXEC}, must also be set already. @param addressFamily: The address family (sometimes called I{domain}) of the existing socket. For example, L{socket.AF_INET}. @return: A new instance of C{cls} wrapping the socket given by C{fd}. """ port = socket.fromfd(fd, addressFamily, cls.socketType) interface = port.getsockname()[0] self = cls(None, factory, None, interface, reactor) self._preexistingSocket = port return self
Example #6
Source File: daemon.py From luscan-devel with GNU General Public License v2.0 | 6 votes |
def is_socket(fd): """ Determine if the file descriptor is a socket. Return ``False`` if querying the socket type of `fd` raises an error; otherwise return ``True``. """ result = False file_socket = socket.fromfd(fd, socket.AF_INET, socket.SOCK_RAW) try: socket_type = file_socket.getsockopt( socket.SOL_SOCKET, socket.SO_TYPE) except socket.error, exc: exc_errno = exc.args[0] if exc_errno == errno.ENOTSOCK: # Socket operation on non-socket pass else: # Some other socket error result = True
Example #7
Source File: _test_multiprocessing.py From ironpython3 with Apache License 2.0 | 6 votes |
def get_high_socket_fd(self): if WIN32: # The child process will not have any socket handles, so # calling socket.fromfd() should produce WSAENOTSOCK even # if there is a handle of the same number. return socket.socket().detach() else: # We want to produce a socket with an fd high enough that a # freshly created child process will not have any fds as high. fd = socket.socket().detach() to_close = [] while fd < 50: to_close.append(fd) fd = os.dup(fd) for x in to_close: os.close(x) return fd
Example #8
Source File: _test_multiprocessing.py From Fluid-Designer with GNU General Public License v3.0 | 6 votes |
def get_high_socket_fd(self): if WIN32: # The child process will not have any socket handles, so # calling socket.fromfd() should produce WSAENOTSOCK even # if there is a handle of the same number. return socket.socket().detach() else: # We want to produce a socket with an fd high enough that a # freshly created child process will not have any fds as high. fd = socket.socket().detach() to_close = [] while fd < 50: to_close.append(fd) fd = os.dup(fd) for x in to_close: os.close(x) return fd
Example #9
Source File: pullpipe.py From learn_python3_spider with MIT License | 6 votes |
def recvfd(socketfd): """ Receive a file descriptor from a L{sendmsg} message on the given C{AF_UNIX} socket. @param socketfd: An C{AF_UNIX} socket, attached to another process waiting to send sockets via the ancillary data mechanism in L{send1msg}. @param fd: C{int} @return: a 2-tuple of (new file descriptor, description). @rtype: 2-tuple of (C{int}, C{bytes}) """ ourSocket = socket.fromfd(socketfd, socket.AF_UNIX, socket.SOCK_STREAM) data, ancillary, flags = recvmsg(ourSocket) [(cmsgLevel, cmsgType, packedFD)] = ancillary # cmsgLevel and cmsgType really need to be SOL_SOCKET / SCM_RIGHTS, but # since those are the *only* standard values, there's not much point in # checking. [unpackedFD] = unpack("i", packedFD) return (unpackedFD, data)
Example #10
Source File: tcp.py From learn_python3_spider with MIT License | 6 votes |
def _fromListeningDescriptor(cls, reactor, fd, addressFamily, factory): """ Create a new L{Port} based on an existing listening I{SOCK_STREAM} socket. Arguments are the same as to L{Port.__init__}, except where noted. @param fd: An integer file descriptor associated with a listening socket. The socket must be in non-blocking mode. Any additional attributes desired, such as I{FD_CLOEXEC}, must also be set already. @param addressFamily: The address family (sometimes called I{domain}) of the existing socket. For example, L{socket.AF_INET}. @return: A new instance of C{cls} wrapping the socket given by C{fd}. """ port = socket.fromfd(fd, addressFamily, cls.socketType) interface = _getsockname(port)[0] self = cls(None, factory, None, interface, reactor) self._preexistingSocket = port return self
Example #11
Source File: core.py From daemonocle with MIT License | 6 votes |
def _is_socket(cls, stream): """Check if the given stream is a socket.""" try: fd = stream.fileno() except ValueError: # If it has no file descriptor, it's not a socket return False sock = socket.fromfd(fd, socket.AF_INET, socket.SOCK_RAW) try: # This will raise a socket.error if it's not a socket sock.getsockopt(socket.SOL_SOCKET, socket.SO_TYPE) except socket.error as ex: if ex.args[0] != errno.ENOTSOCK: # It must be a socket return True else: # If an exception wasn't raised, it's a socket return True
Example #12
Source File: unix.py From learn_python3_spider with MIT License | 6 votes |
def _fromListeningDescriptor(cls, reactor, fd, factory): """ Create a new L{Port} based on an existing listening I{SOCK_STREAM} socket. Arguments are the same as to L{Port.__init__}, except where noted. @param fd: An integer file descriptor associated with a listening socket. The socket must be in non-blocking mode. Any additional attributes desired, such as I{FD_CLOEXEC}, must also be set already. @return: A new instance of C{cls} wrapping the socket given by C{fd}. """ port = socket.fromfd(fd, cls.addressFamily, cls.socketType) self = cls(port.getsockname(), factory, reactor=reactor) self._preexistingSocket = port return self
Example #13
Source File: status_messaging.py From accelerator with Apache License 2.0 | 5 votes |
def _send(typ, message, pid=None): global sock if not sock: fd = int(os.getenv('BD_STATUS_FD')) sock = socket.fromfd(fd, socket.AF_UNIX, socket.SOCK_DGRAM) if len(message) > 1400: message = message[:300] + '\n....\n' + message[-1100:] msg = ('%s\0%d\0%s' % (typ, pid or os.getpid(), message,)).encode('utf-8') for ix in range(5): try: sock.send(msg) return except socket.error as e: print('Failed to send statmsg (type %s, try %d): %s' % (typ, ix, e)) time.sleep(0.1 + ix)
Example #14
Source File: test_socket.py From Project-New-Reign---Nemesis-Main with GNU General Public License v3.0 | 5 votes |
def testFromFd(self): # Testing fromfd() fd = self.cli_conn.fileno() sock = socket.fromfd(fd, socket.AF_INET, socket.SOCK_STREAM) self.addCleanup(sock.close) self.assertIsInstance(sock, socket.socket) msg = sock.recv(1024) self.assertEqual(msg, MSG)
Example #15
Source File: reduction.py From Splunking-Crime with GNU Affero General Public License v3.0 | 5 votes |
def fromfd(fd, family, type_, proto=0): s = socket.fromfd(fd, family, type_, proto) if s.__class__ is not socket.socket: s = socket.socket(_sock=s) return s
Example #16
Source File: app.py From script.tubecast with MIT License | 5 votes |
def force_stop(self): self.stop = True if self.r and not self.r.raw.closed: # Close the underlying socket to kill the ongoing request. sock = socket.fromfd(self.r.raw.fileno(), socket.AF_INET, socket.SOCK_STREAM) sock.shutdown(socket.SHUT_RDWR) sock.close() # request cleanup is handled by __read_cmd_lines
Example #17
Source File: fdunix.py From pth-toolkit with BSD 2-Clause "Simplified" License | 5 votes |
def receive_socket(socket): """This function receives a socket object via a UNIX socket. socket: must be a unix socket Returns a socket object or None if the operation fails. """ iov = IOVec() iov.iov_base = "A" iov.iov_len = 1 cmsg = CMSG() cmsg.cmsg_hdr.cmsg_len = CMSG_LEN(sizeof(c_int)) 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 = recvmsg(socket.fileno(), pointer(msgh), 0) rc = recvmsg(socket.fileno(), pointer(msgh), 0) if rc == -1: errno = get_errno() raise OSError(errno, strerror(errno)) (value,) = unpack_from("i", cmsg.cmsg_data) # the 'mode' parameter should probably passed as part of the message (fd,) = unpack_from("i", cmsg.cmsg_data) newfile = fromfd(fd, AF_INET, SOCK_STREAM) return newfile
Example #18
Source File: _posix_reduction.py From loky with BSD 3-Clause "New" or "Revised" License | 5 votes |
def _rebuild_socket(df, family, type, proto): fd = df.detach() return socket.fromfd(fd, family, type, proto)
Example #19
Source File: reduction.py From Splunking-Crime with GNU Affero General Public License v3.0 | 5 votes |
def rebuild_socket(reduced_handle, family, type_, proto): fd = rebuild_handle(reduced_handle) _sock = fromfd(fd, family, type_, proto) close(fd) return _sock
Example #20
Source File: connection.py From Imogen with MIT License | 5 votes |
def reduce_connection(conn): handle = conn.fileno() with socket.fromfd(handle, socket.AF_INET, socket.SOCK_STREAM) as s: from . import resource_sharer ds = resource_sharer.DupSocket(s) return rebuild_connection, (ds, conn.readable, conn.writable)
Example #21
Source File: reduction.py From Imogen with MIT License | 5 votes |
def send_handle(conn, handle, destination_pid): '''Send a handle over a local connection.''' with socket.fromfd(conn.fileno(), socket.AF_UNIX, socket.SOCK_STREAM) as s: sendfds(s, [handle])
Example #22
Source File: libnetfilter_queue.py From packet-queue with Apache License 2.0 | 5 votes |
def __init__(self): self.handle = nfq.nfq_open() self.fileno = nfq.nfq_fd(self.handle) self.socket = socket.fromfd(self.fileno, socket.AF_UNIX, socket.SOCK_RAW) if nfq.nfq_unbind_pf(self.handle, socket.AF_INET) < 0: raise OSError('nfq_unbind_pf() failed. Are you root?') if nfq.nfq_bind_pf(self.handle, socket.AF_INET) < 0: raise OSError('nfq_bind_pf() failed. Are you root?')
Example #23
Source File: udp.py From learn_python3_spider with MIT License | 5 votes |
def _fromListeningDescriptor(cls, reactor, fd, addressFamily, protocol, maxPacketSize): """ Create a new L{Port} based on an existing listening I{SOCK_DGRAM} socket. @param reactor: A reactor which will notify this L{Port} when its socket is ready for reading or writing. Defaults to L{None}, ie the default global reactor. @type reactor: L{interfaces.IReactorFDSet} @param fd: An integer file descriptor associated with a listening socket. The socket must be in non-blocking mode. Any additional attributes desired, such as I{FD_CLOEXEC}, must also be set already. @type fd: L{int} @param addressFamily: The address family (sometimes called I{domain}) of the existing socket. For example, L{socket.AF_INET}. @param addressFamily: L{int} @param protocol: A C{DatagramProtocol} instance which will be connected to the C{port}. @type proto: L{twisted.internet.protocol.DatagramProtocol} @param maxPacketSize: The maximum packet size to accept. @type maxPacketSize: L{int} @return: A new instance of C{cls} wrapping the socket given by C{fd}. @rtype: L{Port} """ port = socket.fromfd(fd, addressFamily, cls.socketType) interface = port.getsockname()[0] self = cls(None, protocol, interface=interface, reactor=reactor, maxPacketSize=maxPacketSize) self._preexistingSocket = port return self
Example #24
Source File: reduction.py From ironpython3 with Apache License 2.0 | 5 votes |
def recv_handle(conn): '''Receive a handle over a local connection.''' with socket.fromfd(conn.fileno(), socket.AF_UNIX, socket.SOCK_STREAM) as s: return recvfds(s, 1)[0]
Example #25
Source File: reduction.py From ironpython3 with Apache License 2.0 | 5 votes |
def send_handle(conn, handle, destination_pid): '''Send a handle over a local connection.''' with socket.fromfd(conn.fileno(), socket.AF_UNIX, socket.SOCK_STREAM) as s: sendfds(s, [handle])
Example #26
Source File: _test_multiprocessing.py From ironpython3 with Apache License 2.0 | 5 votes |
def _test_closefds(cls, conn, fd): try: s = socket.fromfd(fd, socket.AF_INET, socket.SOCK_STREAM) except Exception as e: conn.send(e) else: s.close() conn.send(None)
Example #27
Source File: tcp.py From learn_python3_spider with MIT License | 5 votes |
def _fromConnectedSocket(cls, fileDescriptor, addressFamily, factory, reactor): """ Create a new L{Server} based on an existing connected I{SOCK_STREAM} socket. Arguments are the same as to L{Server.__init__}, except where noted. @param fileDescriptor: An integer file descriptor associated with a connected socket. The socket must be in non-blocking mode. Any additional attributes desired, such as I{FD_CLOEXEC}, must also be set already. @param addressFamily: The address family (sometimes called I{domain}) of the existing socket. For example, L{socket.AF_INET}. @return: A new instance of C{cls} wrapping the socket given by C{fileDescriptor}. """ addressType = address.IPv4Address if addressFamily == socket.AF_INET6: addressType = address.IPv6Address skt = socket.fromfd(fileDescriptor, addressFamily, socket.SOCK_STREAM) addr = _getpeername(skt) protocolAddr = addressType('TCP', *addr) localPort = skt.getsockname()[1] protocol = factory.buildProtocol(protocolAddr) if protocol is None: skt.close() return self = cls(skt, protocol, addr, None, addr[1], reactor) self.repstr = "<%s #%s on %s>" % ( self.protocol.__class__.__name__, self.sessionno, localPort) protocol.makeConnection(self) return self
Example #28
Source File: test_socket.py From ironpython3 with Apache License 2.0 | 5 votes |
def testFromFd(self): # Testing fromfd() fd = self.cli_conn.fileno() sock = socket.fromfd(fd, socket.AF_INET, socket.SOCK_STREAM) self.addCleanup(sock.close) self.assertIsInstance(sock, socket.socket) msg = sock.recv(1024) self.assertEqual(msg, MSG)
Example #29
Source File: redshift_psql.py From mycroft with MIT License | 5 votes |
def get_connection(self, database): """ gets a connection to the a psql database Args: self.password -- the password to the database Returns: a connection object """ # additional logging to help with connection issues boto_config_dict = self.get_boto_config() self.log_stream.write_msg('boto', extra_msg=boto_config_dict) log_template = "getting connection with host {0} port {1} user {2} db {3}" log_msg = log_template.format(self.host, self.port, self.user, database) self.log_stream.write_msg('starting', extra_msg=log_msg) conn = psycopg2.connect( host=self.host, port=self.port, user=self.user, password=self.password, database=database, sslmode='require') self.log_stream.write_msg('finished', extra_msg=log_msg) fd = conn.fileno() sock = socket.fromfd(fd, socket.AF_INET, socket.SOCK_STREAM) sock.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1) sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPIDLE, self.SECONDS_BEFORE_SENDING_PROBE) sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPINTVL, self.SECONDS_BETWEEN_SENDING_PROBE) sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPCNT, self.RETRIES_BEFORE_QUIT) return conn
Example #30
Source File: unix.py From learn_python3_spider with MIT License | 5 votes |
def _fromConnectedSocket(cls, fileDescriptor, factory, reactor): """ Create a new L{Server} based on an existing connected I{SOCK_STREAM} socket. Arguments are the same as to L{Server.__init__}, except where noted. @param fileDescriptor: An integer file descriptor associated with a connected socket. The socket must be in non-blocking mode. Any additional attributes desired, such as I{FD_CLOEXEC}, must also be set already. @return: A new instance of C{cls} wrapping the socket given by C{fileDescriptor}. """ skt = socket.fromfd(fileDescriptor, socket.AF_UNIX, socket.SOCK_STREAM) protocolAddr = address.UNIXAddress(skt.getsockname()) proto = factory.buildProtocol(protocolAddr) if proto is None: skt.close() return # FIXME: is this a suitable sessionno? sessionno = 0 self = cls(skt, proto, skt.getpeername(), None, sessionno, reactor) self.repstr = "<%s #%s on %s>" % ( self.protocol.__class__.__name__, self.sessionno, skt.getsockname()) self.logstr = "%s,%s,%s" % ( self.protocol.__class__.__name__, self.sessionno, skt.getsockname()) proto.makeConnection(self) return self