I am trying to write a simple socket (server side) to communicate with a process on the same machine, using UDP as Transport Protocol. This is the code:
from socket import *
serverPortS = 1234
serverSocket = socket(AF_INET, SOCK_DGRAM)
serverSocket.bind(('localhost', serverPortS))
print ('Il server e pronto a ricevere')
messageS, clientAddressS =serverSocket.recvfrom(2048)
modifiedMessageS = messageS.upper()
serverSocket.sendto(modifiedMessageS, clientAddressS)
serverSocket.close()
The console gives me the error, just launching the server (no client yet):
Traceback (most recent call last):
File "E:\Laboratorio Python\udp_server.py", line 12, in <module>
serverSocket.bind(('localhost', serverPortS))
OSError: [WinError 10048] Only one usage of each socket address (protocol/network address/port) is normally permitted
I don't know how to fix it or how does it means, and searching on the Web I found more complex problem; would love to hear a possible solution!
Related
I have been working on a project with a raspberry pi. I'm trying to communicate between the laptop and the raspberry pi using sockets.
I was trying a youtube tutorial and keep getting this error
Traceback (most recent call last):
File "", line 1, in
s.recive(1024)
AttributeError: 'socket' object has no attribute 'recive'
after failing to run the script I tried typing the code line by line on python shell
import socket
socket.recv(1024)
but still getting the same error
Can anyone explain whats the problem?
Mind first reading the api and examples?
The correct syntax is buffer = socket.recv(1024)
as noted at socket — Low-level networking interface
But also it seems you are missing other basic flow, like the fact that you have to create the connection first.
Take some time first reading examples of the right use of sockets and then start coding.
A good start would be TutorialsPoint - Python 3 - Network Programming
Problem solved with the help of tutorialspoint.com
Simple server
#!/usr/bin/python3 # This is server.py file
import socket
# create a socket object
serversocket = socket.socket(
socket.AF_INET, socket.SOCK_STREAM)
# get local machine name
host = socket.gethostname()
port = 9999
# bind to the port
serversocket.bind((host, port))
# queue up to 5 requests
serversocket.listen(5)
while True:
# establish a connection
clientsocket,addr = serversocket.accept()
print("Got a connection from %s" % str(addr))
msg = 'Thank you for connecting'+ "\r\n"
clientsocket.send(msg.encode('ascii'))
clientsocket.close()
Simple client
# create a socket object
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# get local machine name
host = socket.gethostname()
port = 9999
# connection to hostname on the port.
s.connect((host, port))
# Receive no more than 1024 bytes
msg = s.recv(1024)
s.close()
print (msg.decode('ascii'))
I'm learning python socket. I tried to connect to a web, but it showed connection error.
I tried to use telnet to connect to the server and it works fine. I also tried another computer and it also works. I'm using MAC OS Mojave, so I don't know what's wrong with the computer. Could anyone give some suggestions?
The code is like this:
import socket
mysock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
mysock.connect(('data.pr4e.org', 80))
cmd = 'GET http://data.pr4e.org/romeo.txt HTTP/1.0\r\n\r\n'.encode()
mysock.send(cmd)
while True:
data = mysock.recv(512)
if len(data) < 1:
break
print(data.decode(),end='')
mysock.close()
The error shows:
Traceback (most recent call last):
File "socket1.py", line 4, in <module>
mysock.connect(('data.pr4e.org', 80))
socket.gaierror: [Errno 8] nodename nor servname provided, or not known
It expected to give the metadata and the data in the website.
Thanks very much in advance!!!!
I have a python program I am using to talk to a microcontroler. It opens the com ports like this:
def STM32_connect():
ports = list(serial.tools.list_ports.comports())
for p in ports:
if "STM32" in p.description:
connection = serial.Serial(p.device, timeout = .01)
return(connection)
print("ERROR: No STM32 Device Found")
sys.exit()
serial_connection = STM32_connect()
And then does a bunch of things, sending and receiving data until I close the program like this with a keyboard interput:
except:
print("\n Program Interrupted...")
finally:
print("\n Closing Serial Port\n")
serial_connection.close()
This all works fine. My problem is when the python script is improperly killed by disconnecting the USB cable or powering off the board I can no longer connect to the micro on any COM port. I receive this error:
Traceback (most recent call last):
File "/home/---/.local/lib/python3.5/site-packages/serial/serialposix.py", line 265, in open
self.fd = os.open(self.portstr, os.O_RDWR | os.O_NOCTTY | os.O_NONBLOCK)
OSError: [Errno 16] Device or resource busy: '/dev/ttyACM2'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "flextester.py", line 1, in <module>
from flex_usb_class import *
File "/home/---/Code/RobotFlexTester/flex_usb_class.py", line 30, in <module>
serial_connection = STM32_connect()
File "/home/---/Code/RobotFlexTester/flex_usb_class.py", line 25, in STM32_connect
connection = serial.Serial(p.device, timeout = .01)
File "/home/---/.local/lib/python3.5/site-packages/serial/serialutil.py", line 240, in __init__
self.open()
File "/home/janey/.local/lib/python3.5/site-packages/serial/serialposix.py", line 268, in open
raise SerialException(msg.errno, "could not open port {}: {}".format(self._port, msg))
serial.serialutil.SerialException: [Errno 16] could not open port /dev/ttyACM2: [Errno 16] Device or resource busy: '/dev/ttyACM2'
I can change COM ports and I receive the exact same error at a different ttyACM port. But I can connect to the same device on the same port if I try to run a different python script. The problem seems to somehow be locked to the initial test script but ps -a does not show it to still be running. The problem goes away without me doing anything after about 30 seconds - 1 min.
the 30s to 1min delay are due to the internals of RS232 protocol. see the closing_wait option ( default 30 sec ) in setserial command ( http://manpages.ubuntu.com/manpages/zesty/man8/setserial.8.html ) when disconnecting USB cable and connection is killed the protocol waits for the time specified in the closing_wait option until it closes the port / session. session_lockout forbids attaching a second process to an open port...
I have an app written in python3 that uses pyserial (python3-serial) to communicate with another processor via serial cable. And I'm losing some responses. I have a tap on the line itself and have determined that the responses are indeed being placed on the wire.
So I wanted to sniff the port at a low linux level to see if the responses are showing up there. My python3 apps uses something like
port = serial.Serial(path, baudrate=115200, timeout=0)
where path is something like _port_TD200_ which is a symlink to \dev\ttyS3.
My general approach was to change that link, so that it points at a virtual port, and then bridge the real port to the virtual port. So I used ln -sf to relink the _port_TD200_ to /tmp/ttyV0 and then run this
sudo socat /dev/ttyS3,raw,echo=0 SYSTEM:'tee input.txt | socat - "PTY,link=/tmp/ttyV0,raw,echo=0,waitslave" | tee output.txt'
However, when I try to restart the service that runs the pyserial app... it chokes on the change:
Traceback (most recent call last):
File "/usr/lib/python3/dist-packages/serial/serialposix.py", line 265, in open
self.fd = os.open(self.portstr, os.O_RDWR | os.O_NOCTTY | os.O_NONBLOCK)
PermissionError: [Errno 13] Permission denied: '/opt/pilot/_port_TD200_'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/opt/pilot/radio.py", line 19, in __init__
self.port = serial.Serial(path, baudrate=115200, timeout=0)
File "/usr/lib/python3/dist-packages/serial/serialutil.py", line 236, in __init__
self.open()
File "/usr/lib/python3/dist-packages/serial/serialposix.py", line 268, in open
raise SerialException(msg.errno, "could not open port {}: {}".format(self._port, msg))
serial.serialutil.SerialException: [Errno 13] could not open port /opt/pilot/_port_TD200_: [Errno 13] Permission denied: '/opt/pilot/_port_TD200_'
I have a guess that the pyserial open machinery which opens a file descriptor, but ALSO does setserial like things, is not happy because /tmp/ttyV0 is not enough of a real serial port. Is this correct? If so, is there a way to modify the socat incantation to make it possible?
Or is it something else? I admit I don't really understand the socat incantation. I pulled it from this stack exchange question...
I know there are some other questions on Sockets, but nothing really worked for me. I am new to this and I work on Python 3.4.
For my server this is my code:
import socket
s = socket.socket()
host = socket.gethostname()
port = 80
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()
My client code:
import socket
s = socket.socket()
host = socket.gethostname
port = 80
s.connect((host, port))
print (s.recv(1024))
s.close
For the SERVER code, I got an error saying:
Traceback (most recent call last):
File "/Users/Gautam/Documents/server.py", line 6, in <module>
s.bind((host, port))
PermissionError: [Errno 13] Permission denied
For the CLIENT I got an error saying:
Traceback (most recent call last):
File "/Users/Gautam/Documents/client.py", line 7, in <module>
s.connect((host, port))
ConnectionRefusedError: [Errno 61] Connection refused
Port numbers below 1024 are reserved for the system, you need to have special privileges to bind sockets to those ports. You need to use another port number, above 1024.
The second error should be pretty simple to figure out, as the error message explicitly say
Connection refused
As the server won't run, how do you expect the client to connect to it?
On a related note, don't use "well-known" port numbers for your own servers, unless you are actually planning to do what the ports are "well-known" for. For example, port 80 is usually used by web-servers, so unless you plan to make a web-server you should not use that port.
Even ports above 1024 are sometimes so called "well-known" ports. Start by checking /etc/services to see the port you picked is commonly available. Do note that some services are pretty obscure and not used very much, but you should still avoid using a port number that's already "reserved" according to /etc/services.