Return a connected socket for sending scan data to it.
183193
def new_scansock (self):
        """"""
        port = None
        try:
            self.sock.sendall("STREAM")
            port = None
            for dummy in range(60):
                data = self.sock.recv(self.sock_rcvbuf)
                i = data.find("PORT")
                if i != -1:
                    port = int(data[i+5:])
                    break
        except socket.error:
            self.sock.close()
            raise
        if port is None:
            raise ClamavError(_("clamd is not ready for stream scanning"))
        sockinfo = get_sockinfo(self.host, port=port)
        wsock = create_socket(socket.AF_INET, socket.SOCK_STREAM)
        try:
            wsock.connect(sockinfo[0][4])
        except socket.error:
            wsock.close()
            raise
        return wsock
775818
def __connect(self):
        """"""
        try:
            logger.debug("Socket connecting to %s:%s", self.host, self.port)
            self.sock.connect((self.host, self.port))
        except socket.error as e:
            logger.exception("socket error %s", e)
            logger.error("Closing socket and recreating a new one.")
            self.sock.close()
            self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            self.sock.connect((self.host, self.port))
1132769
def tcp_client(tcp_addr):
  """"""
  family = socket.AF_INET6 if ":" in tcp_addr.ip else socket.AF_INET
  sock = socket.socket(family, socket.SOCK_STREAM, socket.IPPROTO_TCP)
  for i in range(300):
    logging.info("Connecting to: %s, attempt %d", tcp_addr, i)
    try:
      sock.connect(tcp_addr)
      break
    except socket.error:
      time.sleep(1)
  else:
    sock.connect(tcp_addr)  # One last try, but don't catch this error.
  logging.info("Connected.")

  map_data = read_tcp(sock)
  settings_str = read_tcp(sock)
  if not settings_str:
    raise socket.error("Failed to read")
  settings = json.loads(settings_str.decode())
  logging.info("Got settings. map_name: %s.", settings["map_name"])
  logging.debug("settings: %s", settings)
  settings["map_data"] = map_data
  return sock, settings
992853
def receive(self, sock):
    """"""
    msg = None
    data = b''
    recv_done = False
    recv_len = -1
    while not recv_done:
      buf = sock.recv(BUFSIZE)
      if buf is None or len(buf) == 0:
        raise Exception("socket closed")
      if recv_len == -1:
        recv_len = struct.unpack('>I', buf[:4])[0]
        data += buf[4:]
        recv_len -= len(data)
      else:
        data += buf
        recv_len -= len(buf)
      recv_done = (recv_len == 0)

    msg = pickle.loads(data)
    return msg
863190
def send(self, data):
        

        if self.sock is None:
            if self.auto_open:
                self.connect()
            else:
                raise NotConnected()

        if self.debuglevel > 0:
            print("send:", repr(data))
        blocksize = 8192
        # Python 2.7 array objects have a read method which is incompatible
        # with the 2-arg calling syntax below.
        if hasattr(data, "read") and not isinstance(data, array):
            if self.debuglevel > 0:
                print("sendIng a read()able")
            encode = False
            try:
                mode = data.mode
            except AttributeError:
                # io.BytesIO and other file-like objects don't have a `mode`
                # attribute.
                pass
            else:
                if "b" not in mode:
                    encode = True
                    if self.debuglevel > 0:
                        print("encoding file using iso-8859-1")
            while 1:
                datablock = data.read(blocksize)
                if not datablock:
                    break
                if encode:
                    datablock = datablock.encode("iso-8859-1")
                self.sock.sendall(datablock)
            return
        try:
            self.sock.sendall(data)
        except TypeError:
            if isinstance(data, collections.Iterable):
                for d in data:
                    self.sock.sendall(d)
            else:
                raise TypeError("data should be a bytes-like object "
                                "or an iterable, got %r" % type(data))
305289
def send_scan_request(self):
        ''''''
        command=HCI_Cmd_LE_Scan_Enable(True,False)
        self.transport.write(command.encode())
1119306
def yield_connections(sock):
    """"""
    while True:
        log.debug('waiting for connection on %s', sock.getsockname())
        try:
            conn, _ = sock.accept()
        except KeyboardInterrupt:
            return
        conn.settimeout(None)
        log.debug('accepted connection on %s', sock.getsockname())
        yield conn
1066321
def send(self, data):
        """"""
        bytes_sent = self._sock.send(extract_bytes(data))
        self.bytes_written += bytes_sent
        return bytes_sent
1144622
def scan (data, clamconf):
    
    try:
        scanner = ClamdScanner(clamconf)
    except socket.error:
        errmsg = _("Could not connect to ClamAV daemon.")
        return ([], [errmsg])
    try:
        scanner.scan(data)
    finally:
        scanner.close()
    return scanner.infected, scanner.errors
1322188
def recvline(sock):
    """"""
    reply = io.BytesIO()

    while True:
        c = sock.recv(1)
        if not c:
            return None  # socket is closed

        if c == b'\n':
            break
        reply.write(c)

    result = reply.getvalue()
    log.debug('-> %r', result)
    return result
511992
def get_socket(host, port, timeout=None):
    
    for res in getaddrinfo(host, port, 0, SOCK_STREAM):
        af, socktype, proto, canonname, sa = res
        sock = None
        try:
            sock = socket(af, socktype, proto)
            if timeout is not None:
                sock.settimeout(timeout)
            sock.connect(sa)
            return sock

        except error:
            if sock is not None:
                sock.close()

    raise error
583523
def send(self, data, flags=0):
        '''
        
        '''
        if self._remote_addr == (None,None):
            raise sockerr("ENOTCONN: socket not connected")
        return self._send(data, self._flowaddr())
543894
def socket_reader(connection: socket, buffer_size: int = 1024):
    
    while connection is not None:
        try:
            buffer = connection.recv(buffer_size)
            # no output
            if not len(buffer):
                raise ConnectionAbortedError
        except ConnectionAbortedError:
            # socket closed
            print('connection aborted')
            connection.close()
            yield None
        except OSError:
            # still operate connection after it was closed
            print('socket closed')
            connection.close()
            yield None
        else:
            yield buffer
1227743
def scan(self):
        """"""
        found = []
        for addr in range(0,0x80):
            try:
                self._i2c_bus.read_byte(addr)
            except OSError:
                continue
            found.append(addr)
        return found
1269640
def via_scan():
    
    import socket
    import ipaddress
    import httpfind
    bridges_from_scan = []
    hosts = socket.gethostbyname_ex(socket.gethostname())[2]
    for host in hosts:
        bridges_from_scan += httpfind.survey(
            # TODO: how do we determine subnet configuration?
            ipaddress.ip_interface(host+'/24').network,
            path='description.xml',
            pattern='(P|p)hilips')
        logger.info('Scan on %s', host)
    logger.info('Scan returned %d Hue bridges(s).', len(bridges_from_scan))
    # Confirm Scan gave an accessible bridge device by reading from the returned
    # location.  Should look like: http://192.168.0.1/description.xml
    found_bridges = {}
    for bridge in bridges_from_scan:
        serial, bridge_info = parse_description_xml(bridge)
        if serial:
            found_bridges[serial] = bridge_info

    logger.debug('%s', found_bridges)
    if found_bridges:
        return found_bridges
    else:
        raise DiscoveryError('Scan returned nothing')
1168162
def _port_scan_tcp(self, port):
        """"""
        ret = None

        # Create and configure the scanning socket
        try:
            socket.setdefaulttimeout(port['timeout'])
            _socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        except Exception as e:
            logger.debug("{}: Error while creating scanning socket".format(self.plugin_name))

        # Scan port
        ip = self._resolv_name(port['host'])
        counter = Counter()
        try:
            ret = _socket.connect_ex((ip, int(port['port'])))
        except Exception as e:
            logger.debug("{}: Error while scanning port {} ({})".format(self.plugin_name, port, e))
        else:
            if ret == 0:
                port['status'] = counter.get()
            else:
                port['status'] = False
        finally:
            _socket.close()

        return ret
1334642
def receive_connection():
    
    server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    server.bind(("localhost", 8080))
    server.listen(1)
    client = server.accept()[0]
    server.close()
    return client