简体   繁体   中英

Python cannot bind requests to network interface

I cannot use request proxy to connect to https with my local ip 192.168.1.55 is my local ip

if i hide the https line for proxy, it works, but i know that it is not actually using the proxies

import requests

ipAddress = '192.168.1.55:80'
proxies = {
  "http": "%s" % ipAddress,
  #"https": "%s" % ipAddress,
}

url = 'https://www.google.com'
res = requests.get(url, proxies=proxies)
print res

Result: Response [200]

import requests

ipAddress = '192.168.1.55:80'
proxies = {
  "http": "%s" % ipAddress,
  "https": "%s" % ipAddress,
}

url = 'https://www.google.com'
res = requests.get(url, proxies=proxies)
print res

Result:

requests.exceptions.ProxyError: HTTPSConnectionPool(host='www.google.com', port=443): Max retries exceeded with url: / (Caused by ProxyError('Cannot connect to proxy.', error('Tunnel connection failed: 400 Bad Request',)))

I also tried external VPN server which support HTTPS protocol, even the https proxy line is un-hide, it will work

I have multiple IP and would like to use specified ip with the request. I am running it on Win 10 with python 2.7, and I suspect it is due to the SSL problem, yet to confirm with expertise here. (i think i didnt deal with the SSL properly) I tried a lot of ways to deal with the SSL, no luck so far.

you can try this to bind requests to selected adapter/IP but first install requests_toolbelt

pip install requests_toolbelt

then

import requests
from requests_toolbelt.adapters.source import SourceAddressAdapter

# default binding
response = requests.get('https://ip.tyk.nu/').text
print(response)

# bind to 192.168.1.55
session = requests.Session()
session.mount('http://', SourceAddressAdapter('192.168.1.55'))
session.mount('https://', SourceAddressAdapter('192.168.1.55'))
response = session.get('https://ip.tyk.nu/').text
print(response)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM