Simple Python Web Server Responds to cURL and Epiphany, Not Firefox - python

I am implementing a SIMPLE web server in Python 3 for learning purposes. Currently, all I am trying to get the server to do is receive (and eventually parse) an HTTP request. The code is as follows:
from socket import *
import sys
serverName = getfqdn(gethostname())
serverPort = 13544
# prepare serverSocket for listening
serverSocket = socket(AF_INET, SOCK_STREAM)
serverSocket.bind(('', serverPort))
serverSocket.listen(1)
print('The server is ready to recieve on {}:{}.'.format(serverName, serverPort))
# handle requests
while True:
connectionSocket, address = serverSocket.accept()
print('Accepted a connection from {}:{}.'.format(address[0], address[1]))
message = connectionSocket.recv(2048).decode()
print('Recieved a message from {}:{}:'.format(address[0], address[1]))
message = message.split('\n')
for line in message:
if not line == '' and not line[0] == ' ':
print(' ' + line)
Using "curl localhost:13544" yields output on the server terminal. Navigating to "localhost:13544" in Epiphany yields output on the server terminal. However, navigating to "localhost:13544" in Firefox yields no output. Firefox simply reports that a connection to the host could not be established. Any ideas what the difference could be?

Related

TCP server gets stuck until a second client makes a request

This is the client
from socket import *
import sys
clientsocket = socket(AF_INET, SOCK_STREAM)
host = "localhost"
port = 10000
message = "Hello"
try:
clientsocket.connect((host,port))
except Exception as data:
print (Exception,":",data)
print ("try again.\r\n")
sys.exit(0)
clientsocket.send(message.encode())
print(message.encode())
response = clientsocket.recv(1024)
print (response)
clientsocket.close()
This is the server
from socket import *
import time
client_facing_port = 10000
router_client_socket = socket(AF_INET, SOCK_STREAM)
router_client_socket.bind(("localhost", client_facing_port))
print ('the router is up on port:',client_facing_port)
router_client_socket.listen(0);
while True:
print ('Ready to serve...')
connectionSocket, addr = router_client_socket.accept()
print(router_client_socket.accept())
try:
message = connectionSocket.recv(1024)
if len(message.split())>0:
print (message,'::',message.split()[0])
connectionSocket.send("Hello to you too".encode())
connectionSocket.send("\r\n".encode())
connectionSocket.close()
except IOError:
connectionSocket.send("something went wrong")
connectionSocket.close()
router_client_socket.close()
connectionSocket.close()
Very basic, I'm just trying to understand how sockets work in python.
Here's the problem, if I fire up the server the console prints
the router is up on port: 10000
Ready to serve...
and when I start the client its console prints
b'Hello'
basically the server gets stuck on connectionSocket, addr = router_client_socket.accept()
here's what I don't get, if I fire up a second client the console (of the second client) reads
ConnectionResetError: [WinError 10054] An existing connection was
forcibly closed by the remote host
which makes sense because the server is not multithread and can only handle one client at any given time since I used router_client_socket.listen(0), but the transaction between the first client and the server gets unstuck and completed! The first client receives the "hello to you too" message and prints it out.
What's causing this?
this is on python 3.9 using Spyder on Anaconda

Simple Python TCP Server Not Sending the Entire Web Page

I'm a beginner compsci student and I'm trying to code a simple server in python that takes a .HTML page stored in the same directory and sends it to a client on the same network using a TCP connection.
This is my code:
from socket import *
serverPort = 8000
serverSocket = socket(AF_INET, SOCK_STREAM)
# Prepare a sever socket
serverSocket.bind(('', serverPort)) # binds socket to port 8000
serverSocket.listen(1) # waiting for client to initiate connection
while True:
# Establish the connection
print('Ready to serve...')
connectionSocket, addr = serverSocket.accept()
try:
message = connectionSocket.recv(1024)
filename = message.split()[1]
f = open(filename[1:].decode())
outputdata = f.read()
# Send one HTTP header line into socket
http_response = 'HTTP/1.1 200 OK\n'
connectionSocket.send(http_response.encode())
# Send the content of the requested file to the client
for i in range(0, len(outputdata)):
connectionSocket.send(outputdata[i].encode())
connectionSocket.send("\r\n".encode())
connectionSocket.close()
except IOError:
connectionSocket.send("\r\n".encode())
# DO LATER
serverSocket.close()
sys.exit()
And this is my simple html page:
<!DOCTYPE html>
<html>
<body>
<h1>My First Web Page</h1>
<p>You have successfully accessed the Web Server</p>
</body>
</html>
So far whenever I run my server and direct my browser to it, I only get the following served to me:
<p>You have successfully accessed the Web Server</p>
Along with the body and html tags after this. Checking the page source there's no header.
I ran Wireshark while trying to access my server and indeed it seems like I'm only sending through "You have successfully accessed the Web server" and onwards. This is despite the fact a print function shows I am definitely sending all the data in the file through the TCP connection.
Does anyone know what the issue is?
After sending the protocol answer and headers, the actual response comes after two \r\n sequences.
Use this fixed code:
from socket import *
serverPort = 8000
serverSocket = socket(AF_INET, SOCK_STREAM)
# Prepare a sever socket
serverSocket.bind(('', serverPort)) # binds socket to port 8000
serverSocket.listen(1) # waiting for client to initiate connection
while True:
# Establish the connection
print('Ready to serve...')
connectionSocket, addr = serverSocket.accept()
try:
message = connectionSocket.recv(1024)
filename = message.split()[1]
f = open(filename[1:].decode())
outputdata = f.read()
# Send one HTTP header line into socket
http_response = 'HTTP/1.1 200 OK\n'
connectionSocket.send(http_response.encode())
connectionSocket.send("\r\n".encode())
connectionSocket.send("\r\n".encode())
# Send the content of the requested file to the client
for i in range(0, len(outputdata)):
connectionSocket.send(outputdata[i].encode())
connectionSocket.close()
except IOError:
# DO LATER
serverSocket.close()
sys.exit()
I would use the http.server library
import http.server
import socketserver
PORT = 8080
Handler = http.server.SimpleHTTPRequestHandler
with socketserver.TCPServer(("", PORT), Handler) as httpd:
httpd.serve_forever()
source: https://www.afternerd.com/blog/python-http-server/

Server and client issue: socket.gaierror: [Erno 11001] getaddrinfo failed

I'm new to how networking works and I'm trying to write two scripts for a class assignment, one acts as a server and one as a client. Both the server and client scripts are to be run on the same computer and each one uses two different ports (client port and server port). The client should be able to send a message to the server and then get a message back if the send was successful. This is the client code:
from socket import *
serverName = 'hostname'
serverPort = 2000
clientSocket = socket(AF_INET, SOCK_DGRAM)
message = input('Input lowercase sentence:')
clientSocket.sendto(message.encode(), (serverName, serverPort))
modifiedMessage, serverAddress = clientSocket.recvfrom(3000)
print(modifiedMessage.decode())
clientSocket.close()
And this is the server code:
from socket import *
serverPort = 2000
serverSocket = socket(AF_INET, SOCK_DGRAM)
serverSocket.bind(('', serverPort))
print("The server is ready to receive")
while True:
message, clientAddress = serverSocket.recvfrom(3000)
modifiedMessage = message.decode().upper()
serverSocket.sendto(modifiedMessage.encode(), clientAddress)
The server code runs fine but I get this error from running the client code:
socket.gaierror: [Erno 11001] getaddrinfo failed
Specifically, it doesn't like
clientSocket.sendto(message.encode(), (serverName, serverPort)
I saw multiple threads on here about this error but none of them really helped with my issue. I already checked to ensure both the ports are definitely open before executing both scripts, and they are. My initial guess is that it can't find the actual server port, even though it's up and running and waiting for a response. So I'm stumped. What does this error mean and how can I resolve this?
You forgot to actually connect the client socket to the server socket before trying to send a message:
from socket import *
serverName = 'localhost'
serverPort = 2000
clientSocket = socket(AF_INET, SOCK_DGRAM)
clientSocket.connect((serverName, serverPort))
message = input('Input lowercase sentence:')
clientSocket.sendto(message.encode(), (serverName, serverPort))
modifiedMessage, serverAddress = clientSocket.recvfrom(3000)
print(modifiedMessage.decode())
clientSocket.close()
I also changed the serverName to localhost.

Python local UDP client won't accept messages from local server when using hostname

I'm following the book "Foundations of Python Network Programming". It has an example of a UDP server/client that can send messages to each other. Here is what it looks like
import socket, sys
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
MAX = 65535
PORT = 1060
if 2<= len(sys.argv) <=3 and sys.argv[1] == 'server':
interface = sys.argv[2] if len(sys.argv) > 2 else ''
s.bind((interface, PORT))
print('Listening at {}'.format(s.getsockname()))
while True:
data, address = s.recvfrom(MAX)
print('The client at {} says: {}'.format(address, repr(data)))
msg = 'Your data was {} bytes'.format(len(data))
s.sendto(msg.encode('utf-8'), address)
elif len(sys.argv)==3 and sys.argv[1]=='client':
hostname = sys.argv[2]
s.connect((hostname, PORT))
print('Client socket name is {}'.format(s.getsockname()))
s.send(b'This is another message')
s.settimeout(5.0)
data = s.recv(MAX)
print('The server says', repr(data)) code here
I start the server on my local machine:
python listing2-2.py server
Listening at ('0.0.0.0', 1060)
Then I run my client
python listing2-2.py client 127.0.0.1
Client socket name is ('127.0.0.1', 59535)
The server says b'Your data was 23 bytes'
And everything is fine. I can use localhost and that works too. But if I use my hostname
python listing2-2.py client <myhostname>
Client socket name is ('127.0.0.1', 45677)
and the client times out. The server receives the message from the client (I see the output "This is another message" on the server side), but the client seems to be refusing the message from the server. I'm trying to understand why.

Web Server & Socket Programming

Currently doing an assignment in which we are programming sockets in python and thus creating a web server when the webserver.py code is executed.The code should then display HTTP headers and other information when you access a file(test.html)from the web server. Now my code works (or I'd like to believe so) and I have created a test.html file and the question goes on to say that I should place the test.html file in the same directory as the web server, where exactly is that on my local machine? I placed the test.html in the same folder as webserver.py in the python's root directory and proceeded to 127.0.0.1:1336/test.html to test my code but it doesn't work, where exactly on my machine is the webserver directory in which I should place test.html? Is it that I have to use wamp/xamp and place the test.html in there?
N.B 1336 is the port I specified in the code to connect to.
#import socket module
from socket import *
serverSocket = socket(AF_INET, SOCK_STREAM)
#Prepare a sever socket
serverPort = 1336
serverSocket.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
serverSocket.bind(('', serverPort)) #set up socket connection
serverSocket.listen(1) #tells the server to try a maximum of one connect request before ending connection
while True:
#Establish the connection
print 'Ready to serve...'
connectionSocket, addr = serverSocket.accept()
print 'connected to port',serverPort
try:
message = connectionSocket.recv(1024) #Makes it so that you can recieve message from client
filename = message.split()[1]
f = open(filename[1:])
outputdata = f.open(filename[1:])
#Send one HTTP header line into socket2
#Fill in start
connectionSocket.send('HTTP/1.0 200 OK\r\n')
#Send the content of the requested file to the client
for i in range(0, len(outputdata)):
connectionSocket.send(outputdata[i])
connectionSocket.close()
except IOError:
#Send response message for file not found
print '404 Error : File Not Found.'
#Close client socket
connectionSocket.close()
serverSocket.close()
First of all, you shouldn't use the socket module to make a HTTP server. I recommend using the http.ser ver module, and change the working directory to where the html files are. Lets say i had test.html in C:\User\Desktop.
An example:
from http.server import HTTPServer, CGIHTTPRequestHandler
import os
os.chdir("C:/User/Desktop")
address = ("", 1336)
httpserver = HTTPServer(address,, CGIHTTPRequestHandler)
httpserver.serve_forever()
Then you can access it by 127.0.0.1:1336/test.html
If this isn't the answer you are looking for, please add the webserver.py to the question.

Categories

Resources