Python Socket accept() Timeout - python

Using sockets, the below Python code opens a port and waits for a connection. Then, it sends a response when a connection is made.
import socket
ip = 127.0.0.1
port = 80
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind((ip, port))
s.listen(1)
conn, addr = s.accept()
conn.send(response)
conn.close()
If a connection is not established within 10 seconds, I would like it to move on. Is there a way to define a timeout for s.accept()?
s.accept(timeout=10)
Maybe something like the above line?
Thanks in advance for your help!

to set a timeout for socket s before you connect listen do s.settimeout(10)
edit
I assume it works when listening

Use socket.settimeout:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.settimeout(10)
timeout = False
while not timeout:
try:
(conn, addr) = s.accept()
except socket.timeout:
pass
else:
# your code
To make a 10 second timeout the default behavior for any socket, you can use
socket.setdefaulttimeout(10)

Related

Python Socket connect from another network

I had done port forwarding which ask me for Internal IP, Internal Port, External Port and Protocol.
For internal ip i write device's ip which server.py runs in, for internal and external ports 23456, and for protocol i choose TCP
Server.py
import socket
port = 23456
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(('', port))
s.listen(1)
except socket.error as msg:
print(msg)
while True:
c, addr = s.accept()
txt = 'Connected'
print(addr)
c.send(txt.encode('utf-8'))
c.close
Client.py
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
port = 23456
try:
s.connect(('public ip address',port))
re = s.recv(1024)
print(re.decode('utf-8'))
s.close()
except socket.error as msg:
print(msg)
When i start Server.py and Client.py later, nothing happens. Looks like it doesn't connect to the server.I run both files on same device (i think it isn't problem) (and i can't try it on devices which at different networks for now)
Try binding to address 0.0.0.0
How to:
s.bind(('', port))
into
s.bind(('0.0.0.0', port))
And a reminder to change c.close into c.close() on Server.py

Can't get client to connect to server

I'm just very confused still about the basic socket process. Tried multiple ways to try and get the socket to connect but it keeps refusing.
client code- socket_client.py
import socket
host = socket.gethostname()
port = 8080
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.connect((host,port))
res = client.send (b' testing data send...')
client.close()
server code- server_client.py
import socket
host = socket.gethostname()
port = 8080
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind((host, port))
server.listen(10)
x=0
server_data = []
while True:
conn, addr = server.accept()
data = conn.recv(4096).decode()
x += 1
print ('Servicing client at %s'%addr[0])
server_data = client.recv(4096)
client_close()
server.close()
You have some problems in your server. You read from the connection but never use it, and you do client.recv when there is no variable client. This works:
import socket
host = socket.gethostname()
port = 8080
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind((host, port))
server.listen(10)
x=0
server_data = []
while True:
conn, addr = server.accept()
x += 1
print ('Servicing client at %s'%addr[0])
data = conn.recv(4096).decode()
print( "Received", data )
conn.close()
server.close()
Do remember that Python has a SocketServer module that can make some of this easier. If you need to get fancier, there are few modules better than Twisted at this kind of thing.
ALSO remember that the server must be running before you start the client. Someone has to be listening, otherwise the connection is rejected.

How to connect with Python Sockets to another computer on the same network

So I was trying to figure out a way to use sockets to make a terminal-based chat application, and I managed to do it quite well. Because I could only test it on one computer, I didn't realize that it might not work on different computers. My code is as simple as this:
# Server
import socket
HOST = "0.0.0.0"
PORT = 5555
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.bind((HOST, PORT))
s.listen()
while True:
conn, addr = s.accept()
with conn:
print("Connected to", addr)
data = conn.recv(1024)
print("Received:", data.decode())
conn.sendall(data)
# Client
import socket
HOST = "192.168.0.14"
PORT = 5555
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.connect((HOST, PORT))
s.sendall(b"Hello this is a connection")
data = s.recv(1024)
print("Received:", data.decode())
I've tried changing the ip to 0.0.0.0, use gethostname a lot of other things, but it just doesn't work. The server is up and running, but the client can't connect. Can someone help me?
I believe that 0.0.0.0 means connect from anywhere which means that you have to allow port 5555 through your firewall.
Instead of 0.0.0.0 use localhost as the address in both the client and the server.
I just tested your code using localhost for the server and the client and your program worked.
server:
Connected to ('127.0.0.1', 53850)
Received: Hello this is a connection
client:
Received: Hello this is a connection
As you can see, all that I changed was the address on both the server and the client. If this doesn't work then there is something outside of your program that is preventing you from success. It could be a permissions issue or another program is listening on port 5555.
server.py
# Server
import socket
HOST = "0.0.0.0"
HOST = "localhost"
PORT = 5555
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.bind((HOST, PORT))
s.listen()
while True:
conn, addr = s.accept()
with conn:
print("Connected to", addr)
data = conn.recv(1024)
print("Received:", data.decode())
conn.sendall(data)
if __name__ == '__main__':
pass
client.py
# Client
import socket
HOST = "localhost"
PORT = 5555
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.connect((HOST, PORT))
s.sendall(b"Hello this is a connection")
data = s.recv(1024)
print("Received:", data.decode())
if __name__ == '__main__':
pass

cannot terminate process with socket.accept

I am writing a simple python proxy with Python 3.8 on Windows 10
If I use socket.accept I cannot terminate the process from console neither of these work: ctrl+c, ctrl+z, ctrl+d, break, ctrl+break, only closing the terminal.
I found in the docs this PIP https://www.python.org/dev/peps/pep-0475/ that is about retrying system calls on interrupts. I believe this is the reason why I cannot terminate the app.
Can anyone tell me a best practice how to terminate an app with a blocking socket.accept
Thanks in advance
my code:
import socket
bind_ip = "127.0.0.1"
bind_port = 9999
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
server.bind((bind_ip, bind_port))
server.listen(5)
print("[*] Listening on {}:{}".format(bind_ip, bind_port))
def handle_client(client_socket):
request = client_socket.recv(1024)
print("received: " + request.decode('ascii'))
client_socket.send("ACK".encode('ascii'))
client_socket.close()
while True:
client, addr = server.accept()
print("[*] accepted {}:{}".format(addr[0], addr[1]))
handle_client(client)
The socket might be in a TIME_WAIT state from the earlier trials & executions of your code.
You can use this flag to mitigate this, socket.SO_REUSEADDR
Under the Python Socket Documentation, you can set the flag like this.
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind((HOST, PORT))
You can also look into setting a timeout for the socket!

Python Socket connect two devices on same network

I am attempting to connect a simple server and client from two computers on the same network. Both the client and server cannot 'find' each other, as they do not move past .connect() and .accept() respectively. What am I doing wrong?
(Windows 10)
Server:
import socket
HOST = socket.gethostname() #Returns: "WASS104983"
#I have also tried socket.gethostbyname(socket.gethostname)), returning: "25.38.252.147"
PORT = 50007
sock = socket.socket()
sock.bind((HOST, PORT))
sock.listen(5)
print("Awaiting connection... ")
(clnt, addr) = sock.accept()
print("Client connected")
…
and Client:
import socket
HOST = "WASS104983" #Or "25.38.252.147", depending on the servers setup
PORT = 50007
sock = socket.socket()
print("Attempting connection... ")
sock.connect((HOST, PORT))
print("Connected")
…
I have gotten this to work before so I am not sure why it's not now.
I know there are a few questions of this calibre, but none seem to cover my problem.
Also, a wifi extender should not interfere with local transmissions should it?
I have always seen servers setup as such:
import socket
import threading
bind_ip = '0.0.0.0'
bind_port = 9999
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind((bind_ip, bind_port))
server.listen(5)
print("[*] Listening on {}:{}".format(bind_ip, bind_port))
def handle_client(client_socket):
request = client_socket.recv(1024)
print('received: {}'.format(request))
client_socket.send(b'ACK!')
client_socket.close()
while True:
client, addr = server.accept()
print("[*] Accepted connection from: {}:{}".format(addr[0], addr[1]))
client_handler = threading.Thread(target=handle_client, args=(client,))
client_handler.start()*
Where I think an important distinction from your post may be that the server accepting connections is within an infinite loop. Have you tried this?

Categories