How do I shutdown and close this particular connection?
import socket
import socks
from urllib.request import urlopen
socks.set_default_proxy(socks.SOCKS5, "localhost", 9150)
socket.socket = socks.socksocket
urlopen("http://www.sourceforge.net/")
I've tried socket.socket.shutdown(socket.SHUT_RDWR) but that doesnt work at all:
TypeError: descriptor 'shutdown' requires a '_socket.socket' object but received a 'int'
Related
Basically what I want to do is for me to be able to connect to a proxy while I am able to browse the internet
Here is the code I tried
import webbrowser
import socks, socket, requests
from multiprocessing import Process
def proxy():
while True:
socks.set_default_proxy(socks.SOCKS5, "184.32.91.92", 2901)
socket.socket = socks.socksocket
if __name__ == '__main__':
proxy_process = Process(target=proxy).start()
r = requests.get("http://icanhazip.com")
print(r.content) # stil gives me my actual IP address
webbrowser.open("http://icanhazip.com", new=2) # opening the webbrowser
So i tried to process the proxy to keep the connection alive but even when I open the browser it still gives me my actual IP
Looks like a timing issue. Your __main__ process probably reaches the line:
r = requests.get("http://icanhazip.com")
before proxy_process has done it's job.
So before anyone says its a duplicate, I have seen multiple questions with that error, but could not notice any of that being the same as my problem.
I am trying to make a small project including a socket over SSL, and when trying to catch if a user is trying to connect with a raw socket and not ssl wrapped socket (which is raising a ConnectionResetError) I get a different error.
My code:
import socket
from classes import ClientThread
import ssl
from time import sleep
server = 'localhost'
port = 12345
threads = []
context = ssl.SSLContext(ssl.PROTOCOL_SSLv23)
context.load_cert_chain(certfile="cert.pem", keyfile="cert.pem")
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.bind((server, port))
print(f"[*] server started, listening on port {port}")
while True:
s.listen()
with context.wrap_socket(s, server_side=True) as ssock:
try:
conn, addr = ssock.accept()
client = ClientThread(conn=conn, ip=addr[0], port=addr[1])
client.start()
threads.append(client)
print(f'Threads running: {len(threads)}')
except ConnectionResetError:
print(f'Could not establish ssl handshake with a client.')
The error i get is:
Traceback (most recent call last):
File "C:/Users/x/x/server.py", line 17, in <module>
s.listen()
OSError: [WinError 10038] An operation was attempted on something that is not a socket
I tried setting some sleep time after the exception maybe it needed to reset the socket but didnt hlep, tried to play a bit with the placement of the While True, and while resetting the entire socket help, I dont want to reset all my clients thread just because of a client who didnt try to log in with a SSL socket.
I think it has something to do with the wrap_socket because it modified the socket instance passed to it , but couldnt find a way to unwrap.
Thank you in advance!
listen enables a socket to take incoming connection requests (also called a "passive socket") and establishes a backlog of how many of those requests can be pending in the network stack at any given time. accept accepts one of those connections. You call listen once and accept many times.
Pull the listen outside of the while so that is only called once to establish this as a listening socket.
I'm trying to bind WSGIServer to a IPv6 loopback address:
import socket
import gevent
from gevent.pywsgi import WSGIServer
addrs = socket.getaddrinfo('::1', 8000, socket.AF_INET6, 0, socket.SOL_TCP)
bind_spec = addrs[0][-1]
listener = socket.socket(socket.AF_INET6, socket.SOCK_STREAM)
listener.bind(bind_spec)
server = WSGIServer(
listener,
lambda a,b:'asd'
)
server.serve_forever()
But this only yields
error: [Errno 22] Invalid argument
in
File "/usr/local/lib/python2.7/dist-packages/gevent/server.py", line 122, in _do_accept
client_socket, address = self.socket.accept()
I've tried to use gevent monkeypatcher, that didn't help. Importing gevent AFTER socket creation didn't help either.
IPv6 is enabled on my system. If I replace server construction with plain accept(), socket binds successfully and accepts connections.
listener.listen(5)
listener.accept()
I'm so stupid... GEvent doesn't invoke listen() on the provided socket, so I had to call it myself before creating the server.
I have the following script which uses SocksiPY
and Tor:
from TorCtl import TorCtl
import socks
import socket
socks.setdefaultproxy(socks.PROXY_TYPE_SOCKS5, "127.0.0.1", 9050)
socket.socket = socks.socksocket
import urllib2
import sqlite3
from BeautifulSoup import BeautifulSoup
def newId():
conn = TorCtl.connect(controlAddr="127.0.0.1", controlPort=9051, passphrase="123")
TorCtl.Connection.send_signal(conn, "NEWNYM")
newId()
print(urllib2.urlopen("http://www.ifconfig.me/ip").read())
This code should change Tor identity but it waits for some time and gives the following error:
tuple index out of range
Traceback (most recent call last):
File "template.py", line 16, in <module>
newId()
File "template.py", line 14, in newId
TorCtl.Connection.send_signal(conn, "NEWNYM")
TypeError: unbound method send_signal() must be called with Connection instance as first argument (got NoneType instance instead)
But above script is divided into 2 separate scripts:
import socks
import socket
socks.setdefaultproxy(socks.PROXY_TYPE_SOCKS5, "127.0.0.1", 9050)
socket.socket = socks.socksocket
import urllib2
import sqlite3
from BeautifulSoup import BeautifulSoup
print(urllib2.urlopen("http://www.ifconfig.me/ip").read())
AND:
from TorCtl import TorCtl
def newId():
conn = TorCtl.connect(controlAddr="127.0.0.1", controlPort=9051, passphrase="123")
TorCtl.Connection.send_signal(conn, "NEWNYM")
newId()
When second script is called then first is called it is ok. Can anyone explain what is the problem and how to fix?
Anonymous explained very well this socket overwrite, answer is almost perfect except you have to close the control socket. It is safer because of the TorCtl event loop, but I have to look deeper in the TorCtl code to understand this event loop.
To summarize your code becomes:
from TorCtl import TorCtl
import socks
import socket
socks.setdefaultproxy(socks.PROXY_TYPE_SOCKS5, "127.0.0.1", 9050)
import urllib2
import sqlite3
from BeautifulSoup import BeautifulSoup
__originalSocket = socket.socket
def newId():
''' Clean circuit switcher
Restores socket to original system value.
Calls TOR control socket and closes it
Replaces system socket with socksified socket
'''
socket.socket = __originalSocket
conn = TorCtl.connect(controlAddr="127.0.0.1", controlPort=9051, passphrase="123")
TorCtl.Connection.send_signal(conn, "NEWNYM")
conn.close()
socket.socket = socks.socksocket
newId()
print(urllib2.urlopen("http://www.ifconfig.me/ip").read())
The connection to the control port fails, and conn is assigned the value which Python sockets uses to indicate failure (which is apparently of type NoneType).
The reason is that in the statement socket.socket = socks.socksocket, apparently you're replacing the default socket object or class with one which transparently proxies everything through Tor, which that makes the program try to proxy your control port connection.
The solution is to only perform socket.socket = socks.socksocket after you've opened the control connection (and keep that connection around if you need it later) or save the original socket.socket value so you can switch between values as needed.
Server
import socket
import sys
s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
host= 'VAC01.VACLab.com'
port=int(2000)
s.bind((host,port))
s.listen(1)
conn,addr =s.accept()
data=s.recv(100000)
s.close
CLIENT
import socket
import sys
s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
host="VAC01.VACLab.com"
port=int(2000)
s.connect((host,port))
s.send(str.encode(sys.argv[1]))
s.close()
I want the server to receive the data that client sends.
I get the following error when i try this
CLIENT Side
Traceback (most recent call last):
File "Client.py", line 21, in
s.send(sys.argv[1])
TypeError: 'str' does not support the buffer interface
Server Side
File "Listener.py", line 23, in
data=s.recv(100000)
socket.error: [Errno 10057] A request to send or receive data was disallowed bec
ause the socket is not connected and (when sending on a datagram socket using a
sendto call) no address was supplied
In the server, you use the listening socket to receive data. It is only used to accept new connections.
change to this:
conn,addr =s.accept()
data=conn.recv(100000) # Read from newly accepted socket
conn.close()
s.close()
Your line s.send is expecting to receive a stream object. You are giving it a string. Wrap your string with BytesIO.
Which version of Python are you using? From the error message, I guess you are unintentionally using Python3. You could try your program with Python2 and it should be fine.
try to change the client socket to:
s=socket.socket(socket.AF_INET,socket.SOCK_DGRAM)