Socket connection problem: meet [socket.gaierror] when using socket.connect - python-3.x

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!!!!

Related

Connect TCP socket failed with: 111 (No connection between python in linux and twincat in windows)

I have been trying to get a connection between TwinCAT 3 on Windows and Python on Ubuntu. I already have the connection between Twincat 3 Windows and Python Windows working, but not to Ubuntu. I have a virtual machine set up through Oracle VM Virtualbox. I tried many things but so far had no success in creating the connection.
I have a bridged adapter network and tried to open the port of the IP address of the virtual machine in linux through sudo ufw allow
I have the following code:
pyads.open_port()
pyads.add_route('10.11.104.206.1.1','127.0.0.1')
pyads.close_port()
plc = pyads.Connection('10.11.104.206.1.1', 851)
plc.open()
try:
# try to connect to PLC
plc.read_state()
print('Connection succeeded')
except Exception:
print('Connection failed')
And this is the error I get:
2020-11-22T22:45:46+0100 Error: Connect TCP socket failed with: 111
Traceback (most recent call last):
File "/home/laurence/ws_moveit/devel/lib/moveit_tutorials/move_panda_LKO.py", line 15, in <module>
exec(compile(fh.read(), python_script, 'exec'), context)
File "/home/laurence/ws_moveit/src/moveit_tutorials/doc/move_panda_LKO/scripts/move_panda_LKO.py", line 64, in <module>
pyads.add_route('10.11.104.206.1.1','127.0.0.1')
File "/usr/local/lib/python3.8/dist-packages/pyads/ads.py", line 188, in add_route
return adsAddRoute(adr.netIdStruct(), ip_address)
File "/usr/local/lib/python3.8/dist-packages/pyads/pyads_ex.py", line 155, in wrapper
return fn(*args, **kwargs)
File "/usr/local/lib/python3.8/dist-packages/pyads/pyads_ex.py", line 177, in adsAddRoute
raise ADSError(error_code)
pyads.pyads_ex.ADSError: ADSError: target port not found ADS Server not started (6).
These are the netid/IPadresses.
-
-
-
CX-52EE70
169.254.64.202
5.82.238.112.1.1
TCP_IP
-
LEENLAPTOP19
127.0.0.1
10.11.104.206.1.1
TCP_IP
I have tried combinations with other netid/IP addresses so sometimes I get other errors (110,113) but usually 111 which means connection refused, but I do not know what I am doing wrong. Any ideas?
Please make sure the plc runtime is running (a plc program) when you connect. If the plc is in config or exception mode the plc runtime ads port (851 (or 801 for TC2)) is not present. That is what the ADS error 6 target port not found is trying to tell us.

AttributeError: 'socket' object has no attribute 'recive'

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'))

Why are my COM ports busy?

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...

Why a simple UDP Socket gives me OSError: WinError 10048?

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!

What do the Sockets Error mean and how can I fix them?

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.

Resources