Python Networking - python

So I have create a socket and am using the function socket.bind() and keep on getting the following error: Only one usage of each socket address (protocol/network address/port) is normally permitted
Here is my code:
import socket
s = socket.socket()
host = socket.gethostname()
port = 12345
s.bind((host, port))
s.listen(5)
while True:
c , addr = s.accept()
print('Thank you for connecting to', addr)
c.send('Hello and thanks for connecting')
c.close()

The port / ip combination is bound already. You can not bind it again. You should check if an other instance of your program is still running. If not, use an other port.

Related

TypeError when using AF_INET in the sockets library

I am using the socket library for Python. I'm trying to make a local server. The server runs correctly, but the client does not. When I say that I want to connect to AF_INET it gives me a TypeError. It says that the AF_INET address must be a tuple, when it is a string.
Here is my code:
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(socket.gethostname())
print("client successfully started")
msg = s.recv(1024)
print(msg.decode("utf-8"))
I am using version 3.10.0 (of python), if that helps.
From the socket documentation:
A pair (host, port) is used for the AF_INET address family, where host is a string representing either a hostname in internet
domain notation like 'daring.cwi.nl' or an IPv4 address like
'100.50.200.5', and port is an integer.
For IPv4 addresses, two special forms are accepted instead of a host address: '' represents INADDR_ANY, which is used to bind to
all interfaces, and the string '<broadcast>' represents
INADDR_BROADCAST. This behavior is not compatible with IPv6,
therefore, you may want to avoid these if you intend to support IPv6
with your Python programs.
For a local server, you can just use 'localhost' for the client.
Example:
from socket import *
PORT = 5000
# for server
s = socket() # AF_INET and SOCK_STREAM are the default
s.bind(('',PORT)) # must be a 2-tuple (note the parentheses)
s.listen()
c,a = s.accept()
# for client
s = socket()
s.connect(('localhost',PORT))
The connect function takes in a tuple, so you need an extra set of parentheses. It's not clear what you are trying to do with gethostname. Also, you need to have a port number to connect to. If you are trying to listen to localhost, the code would look like this:
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# Add socket.gethostbyname and add port number
s.connect((socket.gethostbyname(socket.gethostname()), 8089)) # Add another set of parentheses as you need a tuple
print("client successfully started")
msg = s.recv(1024)
print(msg.decode("utf-8"))
Even this may result in a ConnectionRefusedError: [Errno 61] Connection refused error, because you might have to to use the IP address from the server. Something like: 192.168.0.1. To get your IP address, do ipconfig in your cmd prompt (on Windows).
So the correct code would look like this:
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect('192.168.0.1', 8089)) # Your IP instead of 192.168.0.1
print("client successfully started")
msg = s.recv(1024)
print(msg.decode("utf-8"))
I found the answer!
here is the code for everyone that has the same problem as me
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((socket.gethostname(),3000)) #you can use another port if you want
s.listen(5)
print("server successfully started")
while True:
clientsocket, address = s.accept()
print(f"connection has been established from {address}")
clientsocket.send(bytes("Welcome to the chatroom!", "utf-8")) #this sends message to the client in utf-8

I am learning socket but my code but i am not being able to connect to a port

#server
import socket
s = socket.socket()
print("Socket connected")
s.bind((socket.gethostname(),9999))
s.listen(3)
print("waiting for connection")
while True:
c, addr = s.accept()
print("connected with",addr)
c.send(bytes("Welcome!","utf-8"))
c.close()
#client
import socket
c = socket.socket()
c.connect((socket.gethostname(),9999))
msg = c.recv(1024)
print(msg.decode("utf-8"))
i am getting error after running client saying : OSError: [WinError 10048] Only one usage of each socket address (protocol/network address/port) is normally permitted
The error is stating that the port you are trying to bind to is currently in use.
Even if you stop the program, after binding the port remains occupied for a time duration of few minutes.
You need to enable the reuse address option before binding to ports in your code.
Here is how you can do that:
s.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
You can get details in below link :
http://hea-www.harvard.edu/~fine/Tech/addrinuse.html

How to exchange data on different networks using sockets?

I know this was already asked but the previous questions didn't help. I'm trying to send some data using sockets. Specifically I'm using my laptop as server and a Linux emulator (Termux) on my smartphone as a client. Here below you can see the two Python codes. For the server:
import socket
HOST = ''
PORT = 5555
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((HOST, PORT))
s.listen()
conn, addr = s.accept()
print('Connected by', addr)
while True:
data = conn.recv(1024)
if not data:
break
conn.sendall(data)
s.close()
And for the client:
import socket
HOST = ''
PORT = 5555
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((HOST, PORT))
s.sendall(b'Hello, world')
data = s.recv(1024)
print('Received', repr(data))
s.close()
When I'm connected to the same WiFi and in HOST (in both codes) I put the IP I see from ipconfig (192.168.---.---) everything works. It also works if in the HOST of the server I put 0.0.0.0.
However, when I put the IP of the machine (that I can see on https://whatismyipaddress.com/) and instead of using the WiFi I use the phone connection I get: ConnectionRefusedError: [Errno 111] Connection Refused.
Can someone explain me how can I connect client and server when the networks are different? I have been stuck with this for a while.
I also tried to open a port on the Firewall following this procedure and put it in the code instead of 5555 but still it didn't work.
Thank you in advance for the help.

python connect to server on same network

I have got a server.py and a client.py.
If i run them on the same computer using the same port and host as 127.0.0.1 it works fine.
I got another laptop connected to the same network. I got my local ip address 129.94.209.9 and used that for the server. On the other laptop I tried connecting to the server but I couldn't.
Is this an issue with my code, with the network or I'm just using the wrong ip address?
Server.py
HOST = '129.94.209.9'
PORT = 9999
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
server_socket.bind((HOST, PORT))
server_socket.listen(10)
sockfd, addr = server_socket.accept()
send and receive messages etc....
Client.py
HOST = '129.94.209.9'
PORT = 9999
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
sock.connect((HOST, PORT))
except:
print("Cannot connect to the server")
send and receive messages etc...
Client prints "Cannot connect to the server"
Thanks!!
UPDATES: thanks for the comments
1) I did do sockfd, addr = server_socket.accept() sorry I forgot to add it, it was a few lines further down in the code.
2) The error is: [Errno 11] Resource temporarily unavailable
3) Ping does work
EDIT: It is working now when I plug both computers in by ethernet cable to the same network. Not sure why my the won't work when they are right next to each other connected to wifi.
Thanks for all the suggestions! I'll investigate the network issue myself
Using the following code (my IP address rather than yours, of course) I see the expected behaviour.
so8srv.py:
import socket
HOST = '192.168.33.64'
PORT = 9999
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
server_socket.bind((HOST, PORT))
server_socket.listen(10)
print("Listening")
s = server_socket.accept()
print("Connected")
so8cli.py:
import socket
HOST = '192.168.33.64'
PORT = 9999
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
sock.connect((HOST, PORT))
except Exception as e:
print("Cannot connect to the server:", e)
print("Connected")
When I run it, the server prints "Listening". When I then run the client, both it and the server print "Connected".
You will notice that, unlike your code, my client doesn't just print hte same diagnostic for any exception that's raised, but instead reports the exception. As a matter of sound practice you should avoid bare except clauses, since your program will then take the same action whether the exception is caused by a programming error or a user action such as KeyboardInterrupt.
Also try using this construction to obtain the IP address:
HOST=socket.gethostbyname(socket.gethostname())

Python server client socket

I've tried to connect two computers with a socket in Python and I don't know why it doesn't work. The files are from internet and it compiles for me but without any results.
The server.py:
#!/usr/bin/python
import socket
s = socket.socket()
host = ''
port = 12345
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()
and the client.py:
#!/usr/bin/python
import socket
s = socket.socket()
host = # here I put the ip of the server's laptop
port = 12345
s.connect((host, port))
print s.recv(1024)
s.close()
What's wrong?
You have to run the server first. Then run the client at the same time with the IP of the server (I used localhost because it was running on one computer, maybe you should try if that works). The code worked fine for me, every time I ran the client, the server printed a message. If it doesn't work for you, maybe your firewall is not letting you open ports.
Just for the future, please always post any error messages you see.
BTW, isn't this the Python Documentation example for sockets?

Categories