I'm trying to write a simple socket program to connect to the server using specific port. It works fine for the first time (it sends data using 127.0.0.1:8000 to server (127.0.0.1:6000)). However, when I rerun the code, I get below error:
OSError: [WinError 10048] Only one usage of each socket address (protocol/network address/port) is normally permitted
Then after a while, it works again (just once). I think the socket is locked up and needs timeout because I'm not closing/shutdown socket properly but I'm not sure what I'm doing wrong. Any suggestion/comment would be greatly appreciated~!
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
server_address = ('127.0.0.1', 6000)
myIP = '127.0.0.1'
myPort = 8000
sock.bind((myIP,myPort))
sock.connect(server_address)
msg = 'test'
sock.sendall(msg)
sock.shutdown(socket.SHUT_RDWR)
sock.close()
Related
I wrote in vps- console two files, that work great (test message comes from the client and is displayed by the server script).
Server.py:
import socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, True)
sock.bind(('localhost', 8884))
while True:
try:
client, addr = sock.accept()
except KeyboardInterrupt:
sock.close()
break
else:
client.setblocking(True)
result = client.recv(1024)
client.close()
print('Message', result.decode('utf-8'))
Clien.py:
import socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect(('localhost', 8884))
sock.send(b'Test message!')
sock.close()
But if I use Client.py from my home computer, I get an error:
import socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect(('145.148.81.8', 8884)) #ConnectionRefusedError: [Errno 111] Connection refused
sock.send(b'Test message from my house!')
sock.close()
How to fix?
your server code:
sock.bind(('localhost', 8884))
means that the server is only listening for incoming connections on loopback device.
Change that localhost to 0.0.0.0 and then the server listens on all available network devices.
I'm trying to get two computers (my PC and my laptop) to communicate over the Local Network using the Socket module in python.
This is the Server side code running on my PC (connected via LAN):
import socket
HOST = '192.168.1.3' #local PC IP
print(HOST)
PORT = 8080 # Port to listen on (non-privileged ports are > 1023)
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.bind((HOST, PORT))
s.listen()
conn, addr = s.accept()
with conn:
print('Connected by', addr)
while True:
data = conn.recv(1024)
print(data)
if not data:
break
conn.sendall(data)
And this is the Client side code, running on my Laptop (connected over WiFi):
import socket
TCP_IP = '192.168.1.3'
TCP_PORT = 8080
BUFFER_SIZE = 1024
MESSAGE = b"Hello, World!"
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((TCP_IP, TCP_PORT))
s.send(MESSAGE)
data = s.recv(BUFFER_SIZE)
s.close()
print("received data:", data)
The thing is: when I execute both codes, the Server side stays idle waiting for a connection and the Client side, after a while stops and returns the following timeout error:
Traceback (most recent call last):
File "C:\Users\...\client.py", line 13, in <module>
s.connect((TCP_IP, TCP_PORT))
TimeoutError: [WinError 10060] A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond
I can't understand why it won't connect from another device in the same network while it works perfectly if I execute the Client code on the same machine as the Server, even if when I run netstat -an in the CMD I can see the computer listening on that port:
TCP 192.168.1.3:8080 0.0.0.0:0 LISTENING
I tough it had something to do with the port forwarding so I tried playing around with it but I'm having troubles with that too (the ports seem to remain closed).
I really don't know what to do next, if you have some advice or know something else I could try please reply.
It actually was a firewall problem, I just needed to disable the windows defender firewall for the local network and now everything is working fine
In Windows 10, I had to open the port I was using for the socket, and it worked for me.
Here is a link to the instructions.
You're listening and connecting to the same IP - you need to listen to the client's IP(or just any IP with the correct port number) on the server and connect to the server's IP on the client.
For example, if the client's IP is 1.2.3.4 and the server's is 1.2.3.5, then
# server side
s.bind(('1.2.3.4', 8080)) # CLIENT_IP = '1.2.3.4'; PORT = 8080
# can also be s.bind(('0.0.0.0', 8080)) if you want multiple clients to connect.
# client side
s.connect(('1.2.3.5', 8080)) # SERVER_IP = '1.2.3.5'; PORT = 8080
If I have a UDP socket like so:
import socket
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
and the socket can send data:
sock.sendto("message", address)
How do I find out the port of the socket - the port used when sending data to address?
EDIT: I tried sock.getsockname() but this raises an error: [Errno 10022] An invalid argument was supplied
I'm not too familiar with the python socket class, but based on what I've read here https://docs.python.org/2/library/socket.html#socket.getnameinfo
perhaps
socket.getnameinfo()[1] might work
since .getsockname() returns a 2-tuple (host, port)
The socket must be bound before you can use .getsockname() by doing sock.bind(('', 0)).
Hope this helps!
I am a beginner in python socket programming. My question is, I have a TCP server in listen mode at that time client will send data to the server. But when my TCP server is unavailable at that I want a client to go and check for connection every time (something like try exception method with while loop).
I have tried tricks but that didn't work out, it gives o/p like connection refused when my TCP server is unavailable. Below is my code help me with same.
# client.py
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host = socket.gethostname()
port = 2195
s.connect((host, 2195))
while 1:
try:
print "Try loop"
s.sendall("Welcome to Python\r\n")
print "Try loop2"
time.sleep(5)
except:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((host, port))
s.close()
I have tried many solutions but below code works for me.
client.py
import socket
import time
while True:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR,1)
host = socket.gethostname()
port = 2195
try:
s.connect((host , port))
s.sendall("Welcome to Python\r\n")
except:
print "Error"
time.sleep(5)
s.close()
I learned sockets in python. When I tried to programming sockets script in one computer, it worked, but when I tried to programming sockets script with two different computers and open socket with connection, it didn't work.
One computer(the server):
import socket
s = socket.socket()
host = socket.gethostname()
port = 1234
s.bind((host, port))
s.listen(5)
while True:
c, addr = s.accept()
print 'Got connection from', addr
c.send('Thank you for connecting')
c.close()
Second computer(the client):
import socket
s = socket.socket()
host = raw_input("The ip you want to connect to: ")
port = 1234
s.connect((host, port))
print s.recv(1024)
Error:
socket.error: [Errno 10061]
What is the problem in the scripts? Why it doesn't work?
Errno 10061:
It means the server you are trying to connect to is not waiting for one.
Make sure you have the port number open.
Try killing all python processes and start server again.
Update
Instead of
host = socket.gethostname()
use
host = ""