Python socket.timeout() Examples

The following are 30 code examples for showing how to use socket.timeout(). These examples are extracted from open source projects. 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 check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module socket , or try the search function .

Example 1
Project: serializekiller   Author: johndekroon   File: serializekiller.py    License: The Unlicense 7 votes vote down vote up
def jenkins(url, port):
    try:
        cli_port = False
        ctx = ssl.create_default_context()
        ctx.check_hostname = False
        ctx.verify_mode = ssl.CERT_NONE
        try:
            output = urllib2.urlopen('https://'+url+':'+port+"/jenkins/", context=ctx, timeout=8).info()
            cli_port = int(output['X-Jenkins-CLI-Port'])
        except urllib2.HTTPError, e:
            if e.getcode() == 404:
                try:
                    output = urllib2.urlopen('https://'+url+':'+port, context=ctx, timeout=8).info()
                    cli_port = int(output['X-Jenkins-CLI-Port'])
                except:
                    pass
        except:
            pass 
Example 2
Project: ALF   Author: blackberry   File: SockPuppet.py    License: Apache License 2.0 6 votes vote down vote up
def connect(self):
        if self.is_server:
            log.debug("waiting for client to connect...")
            s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            s.bind(('', self.port))
            s.settimeout(0.1)
            start_time = time.time()
            s.listen(0)
            while True:
                try:
                    conn, _ = s.accept()
                    self.conn = conn
                    break
                except socket.timeout:
                    pass
                if self.timeout > 0 and time.time() - start_time >= self.timeout:
                    s.close()
                    raise RuntimeError("Timeout exceeded (%ds)" % self.timeout)
            self.conn.setblocking(True)
        else:
            log.debug("connecting to server (%s:%d)...", self.ip, self.port)
            self.conn = socket.create_connection((self.ip, self.port), self.timeout) 
Example 3
Project: iSDX   Author: sdn-ixp   File: tnode.py    License: Apache License 2.0 6 votes vote down vote up
def interface_listener_thread(s, baddr, port):
    s.settimeout(10)
    mygeneration = generation
    while True:
        try:
            conn, addr = s.accept()
        except socket.timeout:
            if mygeneration == generation:
                continue
            else:
                output('XX', 'INFO: Listener terminating for ' + baddr + ':' + str(port))
                return
        fromto = addr[0] + ':' + str(addr[1]) + '->' + baddr + ':' + str(port)
        #print 'New connection on ' + baddr + ':' + str(port) + ' from ' + addr[0] + ':' + str(addr[1])
        threading.Thread(target=interface_thread , args=(conn, fromto)).start()


# on-demand thread to consume data 
Example 4
Project: knob   Author: francozappa   File: core.py    License: MIT License 6 votes vote down vote up
def sendHciCommand(self, opcode, data, timeout=2):
        """
        Send an arbitrary HCI packet by pushing a send-task into the
        sendQueue. This function blocks until the response is received
        or the timeout expires. The return value is the Payload of the
        HCI Command Complete Event which was received in response to
        the command or None if no response was received within the timeout.
        """

        queue = Queue.Queue(1)
        try:
            self.sendQueue.put((opcode, data, queue), timeout=timeout)
            return queue.get(timeout=timeout)
        except Queue.Empty:
            log.warn("sendHciCommand: waiting for response timed out!")
            return None
        except Queue.Full:
            log.warn("sendHciCommand: send queue is full!")
            return None 
Example 5
Project: knob   Author: francozappa   File: core.py    License: MIT License 6 votes vote down vote up
def recvPacket(self, timeout=None):
        """
        This function polls the recvQueue for the next available HCI
        packet and returns it. The function checks whether it is called
        from the sendThread or any other thread and respectively chooses
        either the sendThreadrecvQueue or the recvQueue.

        The recvQueue is filled by the recvThread. If the queue fills up
        the recvThread empties the queue (unprocessed packets are lost).
        The recvPacket function is meant to receive raw HCI packets in
        a blocking manner. Consider using the registerHciCallback()
        functionality as an alternative which works asynchronously.
        """

        if not self.check_running():
            return None

        try:
            return self.recvQueue.get(timeout=timeout)
        except Queue.Empty:
            return None 
Example 6
def getreview(domain, cityid, activity, reviewid, timeout, maxretries, basepath, force, pause):
    baseurl = 'http://www.tripadvisor.' + domain + '/ShowUserReviews-g'
    reviewurl = '%s%s-d%s-r%s' % (baseurl, cityid, activity, reviewid)

    path = os.sep.join((basepath, domain, str(cityid), str(activity)))
    filename = os.sep.join((path, str(reviewid) + '.html'))
    if force or not os.path.exists(filename):
        htmlpage = download_page(reviewurl, maxretries, timeout, pause)

        if htmlpage is None:
            print('Error downloading the review URL: ' + reviewurl)
        else:
            if not os.path.exists(path):
                os.makedirs(path)

            with codecs.open(filename, mode='w', encoding='utf8') as file:
                file.write(htmlpage.decode('utf-8')) 
Example 7
Project: XFLTReaT   Author: earthquake   File: TCP_generic.py    License: MIT License 6 votes vote down vote up
def check(self):
		try:
			common.internal_print("Checking module on server: {0}".format(self.get_module_name()))

			server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
			server_socket.settimeout(3)
			server_socket.connect((self.config.get("Global", "remoteserverip"), int(self.config.get(self.get_module_configname(), "serverport"))))
			client_fake_thread = TCP_generic_thread(0, 0, None, None, server_socket, None, self.authentication, self.encryption_module, self.verbosity, self.config, self.get_module_name())
			client_fake_thread.do_check()
			client_fake_thread.communication(True)

			self.cleanup(server_socket)

		except socket.timeout:
			common.internal_print("Checking failed: {0}".format(self.get_module_name()), -1)
			self.cleanup(server_socket)
		except socket.error as exception:
			if exception.args[0] == 111:
				common.internal_print("Checking failed: {0}".format(self.get_module_name()), -1)
			else:
				common.internal_print("Connection error: {0}".format(self.get_module_name()), -1)
			self.cleanup(server_socket)

		return 
Example 8
Project: XFLTReaT   Author: earthquake   File: ICMP.py    License: MIT License 6 votes vote down vote up
def __init__(self):
		super(ICMP, self).__init__()
		self.icmp = ICMP_Proto()
		self.ICMP_sequence = 0
		# identifier lottery
		self.ICMP_identifier = int(random.random() * 65535)
		# serverport lottery, not like it matters
		self.ICMP_fake_serverport = int(random.random() * 65535)
		# prefix to make it easier to detect xfl packets
		self.ICMP_prefix = "XFL"
		self.timeout = 2.0
		# if the recv-sent>threshold:
		self.TRACKING_THRESHOLD = 50
		# then we cut back the difference with adjust:
		self.TRACKING_ADJUST = 20

		return 
Example 9
Project: XFLTReaT   Author: earthquake   File: UDP_generic.py    License: MIT License 6 votes vote down vote up
def check(self):
		try:
			common.internal_print("Checking module on server: {0}".format(self.get_module_name()))

			server_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
			self.server_tuple = (self.config.get("Global", "remoteserverip"), int(self.config.get(self.get_module_configname(), "serverport")))
			self.comms_socket = server_socket
			self.serverorclient = 0
			self.authenticated = False

			self.do_check()
			self.communication(True)

		except KeyboardInterrupt:
			self.cleanup()
			raise
		except socket.timeout:
			common.internal_print("Checking failed: {0}".format(self.get_module_name()), -1)
		except socket.error:
			self.cleanup()
			raise

		self.cleanup()

		return 
Example 10
Project: wio-cli   Author: Seeed-Studio   File: udp.py    License: MIT License 6 votes vote down vote up
def send(cmd):
    s = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
    s.settimeout(1)
    flag = False
    for i in range(3):
        try:
            s.sendto(cmd, addr)
            while 1:
                data, a = s.recvfrom(1024)
                if 'ok' in data:
                    flag = True
                    break
        except socket.timeout:
            continue
        except:
            break

        if flag:
            break
    s.close()

    return flag 
Example 11
Project: script.module.inputstreamhelper   Author: emilsvennesson   File: utils.py    License: MIT License 6 votes vote down vote up
def _http_request(url, headers=None, time_out=10):
    """Perform an HTTP request and return request"""
    log(0, 'Request URL: {url}', url=url)

    try:
        if headers:
            request = Request(url, headers=headers)
        else:
            request = Request(url)
        req = urlopen(request, timeout=time_out)
        log(0, 'Response code: {code}', code=req.getcode())
        if 400 <= req.getcode() < 600:
            raise HTTPError('HTTP %s Error for url: %s' % (req.getcode(), url), response=req)
    except (HTTPError, URLError) as err:
        log(2, 'Download failed with error {}'.format(err))
        if yesno_dialog(localize(30004), '{line1}\n{line2}'.format(line1=localize(30063), line2=localize(30065))):  # Internet down, try again?
            return _http_request(url, headers, time_out)
        return None

    return req 
Example 12
Project: lifx-python   Author: sharph   File: network.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def recvpacket(timeout = None):
    global connection
    if connection is None:
        connect()
    #connection.settimeout(timeout)
    #try:
    #    lengthdatum, addr = connection.recvfrom(2)
    #except socket.timeout:
    #    return None
    #connection.settimeout(None)
    #try:
    #    (length, ) = struct.unpack('<H', lengthdatum)
    #except struct.error:
    #    connect()
    #    return None
    #data, addr = connection.recvfrom(length - 2)
    try:
        data, addr = connection.recvfrom(1024)
    except socket.timeout:
        return None
    packet = packetcodec.decode_packet(data)
    if debug:
        print('recvpacket(): ', packet)
    return packet 
Example 13
Project: jawfish   Author: war-and-code   File: connectionpool.py    License: MIT License 6 votes vote down vote up
def _raise_timeout(self, err, url, timeout_value):
        """Is the error actually a timeout? Will raise a ReadTimeout or pass"""

        if isinstance(err, SocketTimeout):
            raise ReadTimeoutError(self, url, "Read timed out. (read timeout=%s)" % timeout_value)

        # See the above comment about EAGAIN in Python 3. In Python 2 we have
        # to specifically catch it and throw the timeout error
        if hasattr(err, 'errno') and err.errno in _blocking_errnos:
            raise ReadTimeoutError(self, url, "Read timed out. (read timeout=%s)" % timeout_value)

        # Catch possible read timeouts thrown as SSL errors. If not the
        # case, rethrow the original. We need to do this because of:
        # http://bugs.python.org/issue10272
        if 'timed out' in str(err) or 'did not complete (read)' in str(err):  # Python 2.6
            raise ReadTimeoutError(self, url, "Read timed out. (read timeout=%s)" % timeout_value) 
Example 14
Project: jawfish   Author: war-and-code   File: connection.py    License: MIT License 6 votes vote down vote up
def _new_conn(self):
        """ Establish a socket connection and set nodelay settings on it.

        :return: New socket connection.
        """
        extra_kw = {}
        if self.source_address:
            extra_kw['source_address'] = self.source_address

        if self.socket_options:
            extra_kw['socket_options'] = self.socket_options

        try:
            conn = connection.create_connection(
                (self.host, self.port), self.timeout, **extra_kw)

        except SocketTimeout:
            raise ConnectTimeoutError(
                self, "Connection to %s timed out. (connect timeout=%s)" %
                (self.host, self.timeout))

        return conn 
Example 15
Project: jawfish   Author: war-and-code   File: pyopenssl.py    License: MIT License 6 votes vote down vote up
def recv(self, *args, **kwargs):
        try:
            data = self.connection.recv(*args, **kwargs)
        except OpenSSL.SSL.SysCallError as e:
            if self.suppress_ragged_eofs and e.args == (-1, 'Unexpected EOF'):
                return b''
            else:
                raise
        except OpenSSL.SSL.ZeroReturnError as e:
            if self.connection.get_shutdown() == OpenSSL.SSL.RECEIVED_SHUTDOWN:
                return b''
            else:
                raise
        except OpenSSL.SSL.WantReadError:
            rd, wd, ed = select.select(
                [self.socket], [], [], self.socket.gettimeout())
            if not rd:
                raise timeout('The read operation timed out')
            else:
                return self.recv(*args, **kwargs)
        else:
            return data 
Example 16
Project: Vxscan   Author: al0ne   File: Requests.py    License: Apache License 2.0 6 votes vote down vote up
def __init__(self):
        urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
        requests.packages.urllib3.disable_warnings()

        self.timeout = TIMEOUT
        self.session = requests.Session()
        self.headers = get_ua()

        if COOKIE == 'random':
            plain = ''.join([random.choice('0123456789') for _ in range(8)])
            md5sum = hashlib.md5()
            md5sum.update(plain.encode('utf-8'))
            md5 = md5sum.hexdigest()
            self.headers.update({'Cookie': 'SESSION=' + md5})
        else:
            self.headers.update(COOKIE)

        if SOCKS5:
            ip, port = SOCKS5
            socks.set_default_proxy(socks.SOCKS5, ip, port)
            socket.socket = socks.socksocket 
Example 17
Project: Vxscan   Author: al0ne   File: Requests.py    License: Apache License 2.0 6 votes vote down vote up
def scan(self, url):
        url = verify(url)
        try:
            r = self.session.get(url,
                                 timeout=self.timeout,
                                 headers=self.headers,
                                 verify=False,
                                 stream=True,
                                 allow_redirects=False)
            return r

        except (requests.exceptions.ConnectTimeout, requests.exceptions.ReadTimeout, requests.exceptions.Timeout,
                requests.exceptions.SSLError, requests.exceptions.ConnectionError, ssl.SSLError, AttributeError,
                ConnectionRefusedError, socket.timeout, urllib3.exceptions.ReadTimeoutError, OpenSSL.SSL.WantReadError,
                urllib3.exceptions.DecodeError, requests.exceptions.ContentDecodingError):
            pass
        except Exception as e:
            logging.exception(e) 
Example 18
Project: Vxscan   Author: al0ne   File: Requests.py    License: Apache License 2.0 6 votes vote down vote up
def post(self, url, data):
        url = verify(url)
        try:
            r = self.session.post(url,
                                  data=data,
                                  timeout=self.timeout,
                                  headers=self.headers,
                                  verify=False,
                                  allow_redirects=False)
            return r
        except (requests.exceptions.ConnectTimeout, requests.exceptions.ReadTimeout, requests.exceptions.Timeout,
                requests.exceptions.SSLError, requests.exceptions.ConnectionError, ssl.SSLError, AttributeError,
                ConnectionRefusedError, socket.timeout, urllib3.exceptions.ReadTimeoutError, OpenSSL.SSL.WantReadError,
                urllib3.exceptions.DecodeError, requests.exceptions.ContentDecodingError):
            pass
        except Exception as e:
            logging.exception(e) 
Example 19
Project: Vxscan   Author: al0ne   File: Requests.py    License: Apache License 2.0 6 votes vote down vote up
def request(self, url, method, data=None, headers=None):
        url = verify(url)
        try:
            if method == 'get':
                r = self.session.get(url, timeout=self.timeout, headers=headers, verify=False, allow_redirects=True)
                return r
            else:
                r = self.session.post(url,
                                      data=data,
                                      timeout=self.timeout,
                                      headers=headers,
                                      verify=False,
                                      allow_redirects=False)
                return r
        except (requests.exceptions.ConnectTimeout, requests.exceptions.ReadTimeout, requests.exceptions.Timeout,
                requests.exceptions.SSLError, requests.exceptions.ConnectionError, ssl.SSLError, AttributeError,
                ConnectionRefusedError, socket.timeout, urllib3.exceptions.ReadTimeoutError, OpenSSL.SSL.WantReadError,
                urllib3.exceptions.DecodeError, requests.exceptions.ContentDecodingError):
            pass
        except Exception as e:
            logging.exception(e) 
Example 20
Project: piescan   Author: m57   File: piescan.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def usage():

    banner()    
    print "Usage: %s -t [targets] -p [ports] [options]" % sys.argv[0]
    print ""
    print "Options:"
    print ""
    print "\t{:<10} {:<30}".format("-t", "[target ip]")
    print "\t{:<10} {:<30} {:<40}".format("-p", "[port]", "Examples: ( -p 25 || -p 22,23,24,25 || -p 0-1024 )")
    print "\t{:<10} {:<30} {:<40}".format("-s[TU]", "Scan type ( default = -sT )", "Examples: ( -sT : TCP || -sU : UDP )")
    print "\t{:<10} {:<30}".format("-v", "Verbose output")
    print "\t{:<10} {:<30}".format("--timeout", "[timeout in ms]", "(default=5s)")
    print ""
    print "Examples:"
    print "\n\t%s -sT -t 127.0.0.1 -p 0-65535 -v  - Do a verbose TCP scan of all ports on 127.0.0.1" % sys.argv[0]
    print "\t%s -sU -t 127.0.0.1 -p 0-100       - Do a UDP scan of the first 100 ports on 127.0.0.1" % sys.argv[0]	

    print "" 
Example 21
Project: gist-alfred   Author: danielecook   File: connectionpool.py    License: MIT License 6 votes vote down vote up
def _raise_timeout(self, err, url, timeout_value):
        """Is the error actually a timeout? Will raise a ReadTimeout or pass"""

        if isinstance(err, SocketTimeout):
            raise ReadTimeoutError(self, url, "Read timed out. (read timeout=%s)" % timeout_value)

        # See the above comment about EAGAIN in Python 3. In Python 2 we have
        # to specifically catch it and throw the timeout error
        if hasattr(err, 'errno') and err.errno in _blocking_errnos:
            raise ReadTimeoutError(self, url, "Read timed out. (read timeout=%s)" % timeout_value)

        # Catch possible read timeouts thrown as SSL errors. If not the
        # case, rethrow the original. We need to do this because of:
        # http://bugs.python.org/issue10272
        if 'timed out' in str(err) or 'did not complete (read)' in str(err):  # Python < 2.7.4
            raise ReadTimeoutError(self, url, "Read timed out. (read timeout=%s)" % timeout_value) 
Example 22
Project: gist-alfred   Author: danielecook   File: securetransport.py    License: MIT License 6 votes vote down vote up
def send(self, data):
        processed_bytes = ctypes.c_size_t(0)

        with self._raise_on_error():
            result = Security.SSLWrite(
                self.context, data, len(data), ctypes.byref(processed_bytes)
            )

        if result == SecurityConst.errSSLWouldBlock and processed_bytes.value == 0:
            # Timed out
            raise socket.timeout("send timed out")
        else:
            _assert_no_error(result)

        # We sent, and probably succeeded. Tell them how much we sent.
        return processed_bytes.value 
Example 23
Project: gist-alfred   Author: danielecook   File: pyopenssl.py    License: MIT License 6 votes vote down vote up
def recv(self, *args, **kwargs):
        try:
            data = self.connection.recv(*args, **kwargs)
        except OpenSSL.SSL.SysCallError as e:
            if self.suppress_ragged_eofs and e.args == (-1, 'Unexpected EOF'):
                return b''
            else:
                raise SocketError(str(e))
        except OpenSSL.SSL.ZeroReturnError:
            if self.connection.get_shutdown() == OpenSSL.SSL.RECEIVED_SHUTDOWN:
                return b''
            else:
                raise
        except OpenSSL.SSL.WantReadError:
            if not util.wait_for_read(self.socket, self.socket.gettimeout()):
                raise timeout('The read operation timed out')
            else:
                return self.recv(*args, **kwargs)
        else:
            return data 
Example 24
Project: gist-alfred   Author: danielecook   File: pyopenssl.py    License: MIT License 6 votes vote down vote up
def recv_into(self, *args, **kwargs):
        try:
            return self.connection.recv_into(*args, **kwargs)
        except OpenSSL.SSL.SysCallError as e:
            if self.suppress_ragged_eofs and e.args == (-1, 'Unexpected EOF'):
                return 0
            else:
                raise SocketError(str(e))
        except OpenSSL.SSL.ZeroReturnError:
            if self.connection.get_shutdown() == OpenSSL.SSL.RECEIVED_SHUTDOWN:
                return 0
            else:
                raise
        except OpenSSL.SSL.WantReadError:
            if not util.wait_for_read(self.socket, self.socket.gettimeout()):
                raise timeout('The read operation timed out')
            else:
                return self.recv_into(*args, **kwargs) 
Example 25
Project: gist-alfred   Author: danielecook   File: pyopenssl.py    License: MIT License 6 votes vote down vote up
def wrap_socket(self, sock, server_side=False,
                    do_handshake_on_connect=True, suppress_ragged_eofs=True,
                    server_hostname=None):
        cnx = OpenSSL.SSL.Connection(self._ctx, sock)

        if isinstance(server_hostname, six.text_type):  # Platform-specific: Python 3
            server_hostname = server_hostname.encode('utf-8')

        if server_hostname is not None:
            cnx.set_tlsext_host_name(server_hostname)

        cnx.set_connect_state()

        while True:
            try:
                cnx.do_handshake()
            except OpenSSL.SSL.WantReadError:
                if not util.wait_for_read(sock, sock.gettimeout()):
                    raise timeout('select timed out')
                continue
            except OpenSSL.SSL.Error as e:
                raise ssl.SSLError('bad handshake: %r' % e)
            break

        return WrappedSocket(cnx, sock) 
Example 26
Project: SenseMe   Author: TomFaulkner   File: senseme.py    License: GNU General Public License v3.0 6 votes vote down vote up
def _query(self, msg):
        sock = socket.socket()
        sock.settimeout(5)

        sock.connect((self.ip, self.PORT))
        sock.send(msg.encode("utf-8"))

        try:
            status = sock.recv(1048).decode("utf-8")
            LOGGER.info("Status: " + status)
        except socket.timeout:
            LOGGER.error("Socket Timed Out")
        else:
            # TODO: this shouldn't return data OR False, handle this better
            sock.close()
            LOGGER.info(str(status))
            match_obj = re.match("\(.*;([^;]+)\)", status)
            if match_obj:
                return match_obj.group(1)
            else:
                return False 
Example 27
Project: SenseMe   Author: TomFaulkner   File: senseme.py    License: GNU General Public License v3.0 6 votes vote down vote up
def _queryraw(self, msg):
        """An alternate version of query that does not do a default regex match on the results"""
        sock = socket.socket()
        sock.settimeout(5)

        sock.connect((self.ip, self.PORT))
        sock.send(msg.encode("utf-8"))

        try:
            status = sock.recv(1048).decode("utf-8")
            LOGGER.info("Status: " + status)
        except socket.timeout:
            LOGGER.error("Socket Timed Out")
        else:
            # TODO: this shouldn't return data OR False, handle this better
            sock.close()
            LOGGER.info(str(status))
            return status 
Example 28
Project: ALF   Author: blackberry   File: SockPuppet.py    License: Apache License 2.0 5 votes vote down vote up
def __init__(self, ip=None, is_server=False, port=1701, timeout=60, debug=False):
        self.conn = None
        self.ip = ip
        self.is_server = is_server
        self.port = port
        self.timeout = timeout
        self.debugging = debug
        log.basicConfig(level=log.INFO)
        if self.debugging and log.getLogger().level == log.INFO:
            self.toggle_debug() 
Example 29
Project: ALF   Author: blackberry   File: SockPuppet.py    License: Apache License 2.0 5 votes vote down vote up
def run_cmd(self, cmd_to_run, cmd_timeout=120):
        log.debug("run cmd on target: %s", " ".join(cmd_to_run))
        data = {"cmd":self.RUN,
                "cmd_to_run":cmd_to_run,
                "timeout":cmd_timeout}
        self.send_data(data)
        log.debug("waiting for cmd results...")
        data = self.recv_data()
        if data["cmd"] == self.EXCEPT:
            log.debug("received exception")
            raise self._process_target_except(data)
        assert data["cmd"] == self.RESULT
        return (data["code"], data["output"]) 
Example 30
Project: Starx_Pixiv_Collector   Author: SuzukiHonoka   File: start.py    License: MIT License 5 votes vote down vote up
def proxy_and_sni_switch():
    global proxy_enable, s, sni_bypass, server_ip, dl_server_ip, post_url
    tag = 'Proxy_And_Sni_Switch'
    if proxy_enable:
        print_with_tag(tag, 'Going to connect to your socks5 server..')
        try:
            # socks.set_default_proxy(socks.SOCKS5, proxy_host, int(proxy_port))
            # socket.socket = socks.socksocket
            # socket.timeout = 500
            proxies = {
                "http": "socks5://" + proxy_host + ":" + proxy_port,
                'https': "socks5://" + proxy_host + ":" + proxy_port
            }
            s.proxies = proxies
        except Exception as e:
            print_with_tag(tag, 'An error occurred when setting up the socks5 proxy for request.')
            print_with_tag(tag, e)
            exit()
        else:
            print_with_tag(tag, 'Proxy connection seems successfully created!!')
    else:
        print_with_tag(tag, 'Not using the proxy..')
        if sni_bypass:
            tag = 'Experiment Function: SNI Bypass'
            print_with_tag(tag, 'Starting..')
            ##########################################################
            print_with_tag(tag, 'Using DoH server to get the correct DNS record.')
            server_ip = get_dns_data_from_doh_server('www.pixiv.net', 'A')
            print_with_tag(tag, ['Server IP =>', server_ip])
            dl_server_ip = get_dns_data_from_doh_server('i.pximg.net', 'A')
            print_with_tag(tag, ['DL Server IP =>', dl_server_ip])
            post_url = post_url.replace('accounts.pixiv.net', server_ip)
            print_with_tag(tag, 'Setting up SSLadapter..')
            # common
            s.mount('https://', host_header_ssl.HostHeaderSSLAdapter())
            # download
            print_with_tag(tag, 'SNI Bypass done.')