i want to catch socket.timeout error, here is my code:
import socket
import sys
from time import sleep
print("Server Listening...")
IPparse = "localhost"
Portparse = 4444
serverSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_address = (IPparse, Portparse)
serverSocket.settimeout(5)
serverSocket.bind(server_address)
serverSocket.listen(2)
(server, (ip,port)) = serverSocket.accept()
try:
data = server.recv(16).decode()
if data == "Hello":
print("Hallo Bro")
except socket.timeout as e:
print ("Timeout is over")
print (e)
but when i running that code. i got this error:
Server Listening...
Traceback (most recent call last):
File "C:\Users\astend\Desktop\TA\20180220 - Gabungan Gui - v.1\Socket\terima2.py", line 13, in <module>
(server, (ip,port)) = serverSocket.accept()
File "C:\Users\astend\AppData\Local\Programs\Python\Python36\lib\socket.py", line 205, in accept
fd, addr = self._accept()
socket.timeout: timed out
What key point am I missing here?
You need to do the accept() inside the try block.
Or else don't set the timeout on the listening socket, set it on the accepted sockets.
Related
I would like to create a TCP connection using python library socket. This traffic should be redirected through Tor network but socks.SOCKS5Error: 0x01: General SOCKS server failure is given.
The code below can connect to Tor proxy and gives a new Tor IP.
from stem.control import Controller
from stem import Signal
import socket
import socks
if __name__ == "__main__":
with Controller.from_port(port=9051) as controller:
# Creatting TOR connection
controller.authenticate(password='password')
controller.signal(Signal.NEWNYM)
socks.setdefaultproxy(socks.PROXY_TYPE_SOCKS5, "192.168.1.148", 9050)
socket.socket = socks.socksocket
# Creatting socket connection
new_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host = '192.168.1.148'
port = 50007
new_socket.connect((host, port))
new_socket.sendall('Hello world')
print(new_socket.recv(1024))
This is the error given:
Traceback (most recent call last):
File "/usr/lib/python3.10/site-packages/socks.py", line 809, in connect
negotiate(self, dest_addr, dest_port)
File "/usr/lib/python3.10/site-packages/socks.py", line 443, in _negotiate_SOCKS5
self.proxy_peername, self.proxy_sockname = self._SOCKS5_request(
File "/usr/lib/python3.10/site-packages/socks.py", line 533, in _SOCKS5_request
raise SOCKS5Error("{:#04x}: {}".format(status, error))
socks.SOCKS5Error: 0x01: General SOCKS server failure
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/home/pi/keylogger-project/./tor_proxy_connection.py", line 74, in <module>
tor.__testing_socket_availability__()
File "/home/pi/keylogger-project/./tor_proxy_connection.py", line 66, in __testing_socket_availability__
self.socket.connect((host, port))
File "/usr/lib/python3.10/site-packages/socks.py", line 47, in wrapper
return function(*args, **kwargs)
File "/usr/lib/python3.10/site-packages/socks.py", line 814, in connect
raise GeneralProxyError("Socket error", error)
socks.GeneralProxyError: Socket error: 0x01: General SOCKS server failure
Server side is a simple nc -lvp 50007
Regards
socket.socket = socks.socksocket
...
host = '192.168.1.148'
...
new_socket.connect((host, port))
The target 192.168.1.148 is an IP address reserved for private networks and thus not reachable from the internet. But the nodes on the Tor network are on the internet and thus cannot reach the given target.
Hey!
Am a developer trying to establish a socket connection between my pc and an esp32 connected on the same network.
Code
On esp32(micropython)
import usocket
import network
def do_connect():
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
if not wlan.isconnected():
print('connecting to network...')
wlan.connect('whydoesnt', 'itwork')
while not wlan.isconnected():
pass
print('network config:', wlan.ifconfig())
def connect_socket():
addr = ("192.168.1.4", 80)
s = usocket.socket(usocket.AF_INET, usocket.SOCK_STREAM)
s.connect(addr)
s.send("hello")
s.close()
do_connect()
connect_socket()
On my computer (python3.9)
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(("0.0.0.0", 80))
s.listen(3)
while True:
client, addr = s.accept()
print("Connected by {}".format(addr))
while True:
content = client.recv(32)
if len(content) == 0:
break
else:
print(content)
print("Closing connection")
client.close()
Am hosting the socket server on 0.0.0.0 so that it runs on the wifi network.
Well, the python server works. I tested it using puTTy running on the same pc. I just had to get my ip address from cmd and connect to it using putty.
Error
But, when I tried doing the same with the esp32, it didn't work, and gave me this error:
network config: ('192.168.1.10', '255.255.255.0', '192.168.1.1', '192.168.1.1')
Traceback (most recent call last):
File "<stdin>", line 24, in <module>
File "<stdin>", line 19, in connect_socket
OSError: [Errno 113] ECONNABORTED
Well, thank you in advance! 🎉
I have the following code and it's giving me this error in Python3 in Windows:
OSError: [WinError 10057] A request to send or receive data was disallowed because the socket is not connected and (when sending on a datagram socket using a sendto call) no address was supplied
Could someone help explain why i'm getting this error and how I can avoid it? What I want to do is start 5 threads with different socket numbers and have them do non-blocking receives. Thx in advance.
import threading
import socket
import os
import errno
import sys
from time import sleep
HOST = '127.0.0.1' # Standard loopback interface address (localhost)
def worker(port):
"""thread worker function"""
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.setblocking(False)
s.bind((HOST, port))
s.listen()
print('Thread is listening on', port)
while True:
try:
msg = s.recv(4096)
except socket.timeout as e:
err = e.args[0]
if err == 'timed out':
sleep(1)
print ('No data available')
continue
else:
# a "real" error occurred
print (e)
sys.exit(1)
else:
print (msg)
threads = []
for i in range(10001, 10005):
t = threading.Thread(target=worker(i))
threads.append(t)
t.start()
for thread in threads:
thread.join()
I try to develop a simple server and client program, I run the code with python 3.4.2.( on Debian 8.6 ) . The server run well, the client program connect's to the server but when I pass a text in terminal to send to server and send back with time stamp, I get this error in the client terminal window
Traceback (most recent call last):
File "tcp_client", line 15, in
tcpCliSock.send(data)
TypeError: 'str' does not support the buffer interface
this is the server code
from socket import *
from time import ctime
HOST = '192.168.0.141'
PORT = 21577
BUFSIZ = 1024
ADDR = (HOST, PORT)
tcpSerSock = socket(AF_INET, SOCK_STREAM)
tcpSerSock.bind(ADDR)
tcpSerSock.listen(5)
while True:
print('waiting for connection...')
tcpCliSock, addr = tcpSerSock.accept()
print('....connected from :', addr)
while True:
data = tcpCliSock.recv(BUFSIZ)
if not data:
break
tcpCliSock.send('[%s] %s' % (bytes(ctime(), 'utf-8'), data))
tcpCliSock.close()
tcpSerSock.close()
and this it the client code
from socket import *
HOST = '192.168.0.141'
PORT = 21577
BUFSIZ = 1024
ADDR = (HOST, PORT)
tcpCliSock = socket(AF_INET, SOCK_STREAM)
tcpCliSock.connect(ADDR)
while True:
data = input('> ')
if not data:
break
tcpCliSock.send(data)
data = tcpCliSock.recv(BUFSIZ)
if not data:
break
print(data.decode('utf-8'))
tcpCliSock.close()
I am trying to create a socket server with asyncio where I would asynchronous listen for connection and get each connections incomming message. Howeven I cannot get it working.
Here is my code for server:
import asyncio
import socket, sys
from concurrent.futures import ProcessPoolExecutor
def print_output(csock, loop):
while 1:
print('gotcha')
msg = csock.recv(1024)
if not msg:
pass
else:
print ("Client send: " + msg)
def s_listen(loop):
while True:
(csock, adr) = sock.accept()
print('start another process')
asyncio.ensure_future(loop.run_in_executor(executor, print_output, csock, loop))
print('done')
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) #reuse tcp
sock.bind(('', 12345))
sock.listen(5)
executor = ProcessPoolExecutor()
loop = asyncio.get_event_loop()
listener = asyncio.ensure_future(loop.run_in_executor(executor,s_listen,loop))
print('here')
While this is my code for client
import socket, sys
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect(('', 12345))
sock.send(b"Hello I'm Client.\r\n")
I can get the function "s_listen" running asynchronously but the code got blocked by "print_output" function.
I am new to asyncio, can anyone help?
Thanks!
Asyncio provides a coroutine-based API called stream to manage socket clients and servers. Here's a modified version of the tcp echo server from the user documentation:
import asyncio
# Client handler
async def handle_echo(reader, writer):
while not reader.at_eof():
data = await reader.read(100)
message = data.decode().strip()
print('Client sent: ' + message)
writer.close()
# Start the server
loop = asyncio.get_event_loop()
coro = asyncio.start_server(handle_echo, '', 12345, loop=loop)
server = loop.run_until_complete(coro)
# Serve requests until Ctrl+C is pressed
print('Serving on {}'.format(server.sockets[0].getsockname()))
try:
loop.run_forever()
except KeyboardInterrupt:
pass
# Close the server
server.close()
loop.run_until_complete(server.wait_closed())
loop.close()
You can test this example with the netcat client:
# Client
$ ncat localhost 12345
hello,
world!
# Server
$ python3.5 server.py
Serving on ('0.0.0.0', 12345)
Client sent: hello,
Client sent: world!