AttributeError: 'socket' object has no attribute 'recive' - python-3.x

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

Related

OpenSSL - Raspberry Pi4 failing to communicate to server on windows system

As the title states I get an error trying to communicate from a Raspberry PI 4 and windows system using an SSL connection.
The current client script works perfectly on windows to a server application running on windows.
This is the client script:
from OpenSSL import SSL
import sys, os, select, socket, time
ctx = SSL.Context(SSL.SSLv23_METHOD)
sock = SSL.Connection(ctx, socket.socket(socket.AF_INET, socket.SOCK_STREAM))
sock.connect(('10.0.0.84', 443))
stri = 'hello\r\n'
tobyte = bytes(stri,'utf-8')
print(tobyte)
buf = sock.recv(4096)
while True:
sock.send(tobyte)
time.sleep(60)
The error I get on Raspberry Pi 4:
Traceback (most recent call last): File
"/home/pi/Documents/scripts/openssltest.py", line 15, in
buf = sock.recv(4096)
File "/usr/lib/python3/dist-packages/OpenSSL/SSL.py", line 1791, in recv
self._raise_ssl_error(self._ssl, result) File "/usr/lib/python3/dist-packages/OpenSSL/SSL.py", line 1647, in
_raise_ssl_error
_raise_current_error() File "/usr/lib/python3/dist-packages/OpenSSL/_util.py", line 54, in
exception_from_error_queue
raise exception_type(errors) OpenSSL.SSL.Error: [('SSL routines', 'ssl_choose_client_version', 'unsupported protocol')]
I have the same version of OpenSSL running on the Raspberry Pi and Windows PC
One thing I noticed in Visual Studio Code (for the Raspberry Pi) is that the sock.send() is not recognised but sock.sendall() is. VSC in windows is showing sock.send() as an option.
I am using OpenSSL version 1.1.1k and python 3.7.3 on the Raspberry PI. OpenSSL 1.1.1k and python 3.9.6 on windows. All devices are running on the same network
I have not written the server application but uses a self signed certificate.
Any suggestions would be much appreciated
Adding #mti2935 comment as the answer as this fixed my problem. Just to help anyone in the future
('SSL routines', 'ssl_choose_client_version', 'unsupported protocol')
usually means the server will only allow connections using certain
SSL/TLS protocols (e.g. TLS1.2 or above), but the client does not
support any of the protocols that the server requires (e.g. client
supports TLS1.0 or lower). Can you try connecting to the server from
the command line of the PI, by doing openssl s_client -connect
10.0.0.84:443? Does it connect? If so, what protocol does it use?
The problem was that my client was using a protocol that the server did not support SSLv23_METHOD. Changed the protocol to SSL.TLSv1_METHOD.
Corrected code:
from OpenSSL import SSL
import sys, os, select, socket, time
ctx = SSL.Context(SSL.TLSv1_METHOD)
sock = SSL.Connection(ctx, socket.socket(socket.AF_INET, socket.SOCK_STREAM))
sock.connect(('10.0.0.84', 443))
stri = 'hello\r\n'
tobyte = bytes(stri,'utf-8')
print(tobyte)
buf = sock.recv(4096)
print(buf)
while True:
sock.send(tobyte)
time.sleep(5)

MQTT Broker Connection Refused Error in Python

I have been trying to connect to broker port 1884. But it gets every time connection refused error.
def __init__(self, host='127.0.0.1', port=8080, broker_address='127.0.0.1', broker_port=1884, start_config=None):
self.app = Bottle()
"""Create the http service app"""
self.broker = SimpleBroker(address=broker_address, port=broker_port)
self.broker.start()
"""Create and run the broker (broker always runs as a daemon)"""
self.brokerAddress = broker_address
"""address of the API broker - usually identical to own address, but others for testing"""
self.mqttc = Client()
"""mqtt client for publishing messages to API broker - delivered to edge and preprocessing layer"""
self.mqttc.connect(host=broker_address, port=broker_port)
"""connect to the broker upon startup"""
and then the execution part:
if __name__ == "__main__":
myAPI = APIServer('127.0.0.1', 8080, '127.0.0.1', start_config='all wheels')
myAPI.start()
The error message:
Traceback (most recent call last):
File "/root/PycharmProjects/Thesis2019/API/APIServer.py", line 328, in <module>
myAPI = APIServer('127.0.0.1', 8080, '127.0.0.1', start_config='all wheels')
File "/root/PycharmProjects/Thesis2019/API/APIServer.py", line 42, in __init__
self.mqttc.connect(host=broker_address, port=broker_port)
File "/root/PycharmProjects/Thesis2019/venv/lib/python3.6/site-packages/paho/mqtt/client.py", line 839, in connect
return self.reconnect()
File "/root/PycharmProjects/Thesis2019/venv/lib/python3.6/site-packages/paho/mqtt/client.py", line 962, in reconnect
sock = socket.create_connection((self._host, self._port), source_address=(self._bind_address, 0))
File "/usr/lib/python3.6/socket.py", line 724, in create_connection
raise err
File "/usr/lib/python3.6/socket.py", line 713, in create_connection
sock.connect(sa)
ConnectionRefusedError: [Errno 111] Connection refused
On the other hand when i execute it in debug mode, i got :
[2019-04-09 23:43:05,243] :: WARNING :: hbmqtt.broker.plugins.topic_taboo :: 'topic-check' section not found in context configuration
[2019-04-09 23:43:05,243] :: INFO :: transitions.core :: Exited state new
[2019-04-09 23:43:05,244] :: INFO :: transitions.core :: Entered state starting
[2019-04-09 23:43:05,248] :: INFO :: hbmqtt.broker :: Listener 'default' bind to 127.0.0.1:1884 (max_connections=100)
[2019-04-09 23:43:05,248] :: INFO :: transitions.core :: Exited state starting
[2019-04-09 23:43:05,248] :: INFO :: transitions.core :: Entered state started
Additional to all the connection refused part, it just starts it without problem in debug mode i guess?
The Pycharm is launched with root privilege.
Firewall is checked, and it is disabled.
None of these ports are open, checked it with lsof.
I use Python 3.6, hbmqtt 0.9.5
It works on Windows, but not on Mac or Linux
Why i have connection refused error each time i try to execute it ? What am i missing?
Thanks in advance for the ideas.
The solution is:
The Mosquitto default port connection is set to 1883 in the config file, where I was trying to connect through port 1884.
I thought that, this properties are set whenever you change the number. Which is not correct since they are static. not changing dynamically.(sure there is a way too.)
Apart from that, the API Broker and Broker port numbers have to be swapped. I don't know why but windows can bind on top of it without problems. but Mac OS and Linux are throwing Connection Refused error.
The Pycharm is launched with root privilege.
Firewall is checked, and it is disabled.
None of these ports are open, checked it with lsof.
Check config file of the Mosquitto, if the allow_annoymous is True
Control your port connections 10 times.
These are still valid check before going crazy. %90 of the problems are caused because of one of these issues.
If you have further help or questions, you can comment in here and I will try to help for future inquiries.

Socket connection problem: meet [socket.gaierror] when using socket.connect

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

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