Connecting to Python socket from iOS Safari browser - python

I have a python socket listening on my computer's ip address on a specific port. I am using the standard python socket library with something like the following code:
listen_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
listen_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
listen_socket.bind(server_address) # Server address is a tuple (HOST, PORT) with host being
# something like 123.456.789.00 and port being 4000
listen_socket.listen()
client_connection, client_address = listen_socket.accept()
request_data = client_connection.recv(1024).decode('utf-8')
print(request_data)
When I use Chrome on my iPhone to connect to the address, the rest of my code runs fine and processes the incoming request by sending an html page. When I use Safari, it loads for a while until it fails and a says "Safari cannot open the page because it could not connect to the server."
Funny enough, if I stay on the page, restart the server, and then reload the page using the refresh button, it connects fine. But trying to access the address through the url address does not work. Refreshing using the refresh button seems to work. Why is Safari having trouble connecting to my Python socket?

Try increasing the backlog count in the listen_socket.listen() call.
I had a similar issue with a python 2 socket server and macOS Safari. Safari would say it could not connect to the server, but Chrome/Firefox/IE/curl all worked without any errors. I changed this:
listen_socket.listen(1)
To this:
listen_socket.listen(5)
Safari then worked without any errors. I am now using 128 instead of 5, not sure what the default is in Python 3.
When set to 1, in the python server I would see Safari connect, but then socket.recv() would never return.

Related

how can we print http flow of a browser with python? [Like browser network tab]

In Python i want to build a program like browser network tab, which prints all http/s flows. The same thing needs to be done with python.
[#urllib #requests #basicHTTPRequest etc..] modules are there but how can i get the network traffic of a browser?
can we achieve that by binding socket to proxy of a browser?
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.bind(('0.0.0.0', port))
sock.listen(1)
self._sockets.append(sock)
Need to create a tcp connection over that address and port of a proxy?
suggest me a good resource to achieve.

DNS server doesn't get data python

i built a simple DNS server.. and i'm just trying to print the data (the whole packet) but my server stuck at the recvfrom part.
i tried to open a file that i got as adminstor which changes my DNS server to 127.0.0.1 but it doesn't work.
this is my code:
i tried to write some url's on my browser but my server doesn't get nothing and stuck at the recv.
import socket
myserver = sokcet.socket(socket.AF_INET, socket.SOCKET_DGRAM)
myserver.bind(('0.0.0.0',53))
data, addr = myserver.recvfrom(1024)
print data

building a server, telnet localhost 8888 showing blank screen

so I'm trying to get through this tutorial here .
I started by running the code in a file here:
import socket
HOST, PORT = '', 8888
listen_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
listen_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
listen_socket.bind((HOST, PORT))
listen_socket.listen(1)
print('Serving HTTP on port %s ...' % PORT)
while True:
client_connection, client_address = listen_socket.accept()
request = client_connection.recv(1024)
print(request.decode('utf-8'))
http_response = """\
HTTP/1.1 200 OK
Hello, World!
"""
client_connection.sendall(bytes(http_response, 'utf-8'))
client_connection.close()
then in the next part, it tells me to enter this line on the same computer.
$ telnet localhost 8888
I have webserver1.py running on a different cmd window (in windows). when I run this line though I get a blank screen instead of
$ telnet localhost 8888
Trying 127.0.0.1 …
Connected to localhost.
like I'm supposed to. Does anyone know why? How to fix it? I tried googling telnet localhost 8888 to no avail, I couldn't find a situation where this happened before.
so uh... unless there's an http daemon running/listening on that port, which couldn't happen anyway because of how ports typically work (but not always), that's actually about as far as that exercise will go.
The result you had was correct, based on the output you got after running telnet from another cmd session while that python script was running in the background. However, the windows oobe version of telnet is weaksauce. Using it to send additional commands to communicate with the server once a successful connection is established is kinda booty.
The script invokes the python interpreter (shoulda used #!/usr/bin/env python... just saying) and uses a few objects from the socket lib to open a socket on port 8888 on the localhost (the computer you're currently logged into).
That's it, nothing more. I ran through the exercise too, and gisted it # https://gist.github.com/mackmoe/09de098b3df5c45adf7a17b764a1eec4
Just my 2 cents here:
If you want to setup a server for the experience (and for free), just grab virtualbox, a linux server iso and use one of digital ocean's walkthroughs. Like the one # https://www.digitalocean.com/community/tutorials/how-to-install-linux-apache-mysql-php-lamp-stack-on-ubuntu-16-04
Hope That Helps Friend!

how to get input from html using python socket

I have a code to start a simple socket sever on localhost. However, I want it to display a html page when it is accessed through browser. The html will contain two text fields and submit button. When user enters text in text fields and clicks on submit button, I want the program to read from text fields. How Can I Do That?
The instant answer (I hope so) to your question is in the last section The Answer - and, if I have interpreted your question wrong, let me know in the comment section.
The confusion - You are confusing the fundamentals - to display a html page, you simply need a server (localhost in your case), and the browser will use the HTTP/HTTPS protocol to fetch that content/response/html page. In Python (almost same for other languages) there are two levels of access to network services:
Low-level via sockets.
Higher-level via application level network protocols, like HTTP, FTP, etc.
Sockets - in plain english it is a functionality (interface) provided by the machine's operating system to implement client and server (for the higher-level network protocols) like communication between the processes. These processes can be running on a same machine or both processes on physically apart machines (e.g. requesting a website using browser).
A typical socket client is (asking for the desired html from browser):
client_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client_sock.connect(("localhost", 80))
But to make it work you must already have server running (which will serve the html):
server_sock = socket.socket() # Create a socket object
server_sock.bind((localhost, 80)) # Bind to the port
server_sock.listen(5)
while True:
# lines for whatever we want server to do
The line server_sock.bind((localhost, 80)) has binded (assigned/allocated) the localhost:80 (a socket is basically 'host_name:port_number') to this server_sock i.e. any call/request to localhost:80 will be handled as per the lines in the above while True: block of the code above, can be a text response, HTML, etc.
Typical web scenario - We enter a website name www.google.com (which is resolved into an IP via DNS protocol - a whole another story) and hit enter, we'll get the Google's search homepage in response - Here you're the client, that is entering the website name and hitting enter is technically client_sock.connect('www.google.com', 80), and it only worked because on another (remote) machine/system/host they have server_socket binded and listening i.e.
server_sock.bind('machine's_IP', 80)
server_sock.listen(5)
while True:
#accept connections from outside
(client_socket, address) = server_socket.accept()
# here will be the lines which send us back the Google's
# homepage html as a response to our web request.
To sum-up, servers (webserver in your case) can be implemented using (almost) any programming languages e.g. python or C, etc, but the basis, the lowest layer, exactly where the data is passed between 2 processes whether on the same machine using locahost (loopback) or each process running on physically apart machine/host (typical web scenario ) via the HTTP (TCP) protocol rest upon sockets. Sockets are the fundamental building block from which HTTP, HTTPS, FTP, SMTP protocols (all of these are TCP-type protocols) are defined.
DNS, DHCP, VOIP protocols are UDP protocols but they too are built on top of sockets.
The Answer - To start, create a web_server.py and paste the following code (only to see how it works) and run the file as script i.e. from the file's location run "python
web_server.py" in command prompt/terminal:
#!/usr/bin/env python
import socket
host = 'localhost'
port = 80
server_sock = socket.socket(socket.AF_INET,\
socket.SOCK_STREAM) # Create a socket object
server_sock.bind((host , port)) # Bind to the port
print 'Starting server on', host, port
print 'The Web server URL for this would be http://%s:%d/' % (host, port)
server_sock.listen(5) # Now wait for client connection.
print 'Entering infinite loop; hit CTRL-C to exit'
while True:
# Establish connection with client.
client_sock, (client_host, client_port) = socket.socket.accept()
print 'Got connection from', client_host, client_port
client_sock.recv(1000) # should receive request from client. (GET ....)
client_sock.send('HTTP/1.0 200 OK\n')
client_sock.send('Content-Type: text/html\n')
client_sock.send('\n') # header and body should be separated by additional newline
# you can paste your 2 text field html here in the <body>
client_sock.send("""
<html>
<body>
<h1>Hello World</h1> this is my server!
</body>
</html>
""")
client_sock.close()
P.S. You have to implement a HTTP server (webserver) - which will definitely use the socket interface at the lowest level i.e.
server_sock.bind
server_sock.listen
server_sock.accept

Python socket on Windows 7 is not accessible from another machine

I'm trying to create a Python program that will listen on a socket. I'm using Windows 7 with Python 2.7. Whatever I do, the socket seems to be accessible from the local machine but not from elsewhere on the network.
I've got the following code:
from werkzeug.wrappers import Request, Response
#Request.application
def application(request):
return Response('Hello World!')
if __name__ == '__main__':
from werkzeug.serving import run_simple
# Using empty string or the machine's real IP address here
# gives the same problem
run_simple('0.0.0.0', 4000, application)
If I connect from the local machine I see the response fine. If I execute
$ curl 'http://192.168.1.1:4000/'
from another (linux) box on the network, the curl hangs for a long time before timing out. Wireshark shows that I receive a SYN packet to port 4000 but don't see it ACKed.
I've tried making sure packets to this port are allowed through the firewall (the fact that I see the SYNs in Wireshark suggests this is not the problem). I've tried setting Python to run as administrator (and I've checked that ctypes.windll.shell32.IsUserAnAdmin() returns true). This isn't just Werkzeug, I've tried with SocketServer from the Python standard library as well.
Running Windows Apache on the same port works fine from across the network, which suggests there's no problem with the network or firewall or with my curl request.
netstat -an shows:
TCP 0.0.0.0:4000 0.0.0.0:0 LISTENING
Edit: I've tried with the following minimal code. On the server side (Windows 7):
import socket
s = socket.socket()
s.bind(('', 8080))
s.listen(1)
remotesock, addr = s.accept()
And on the linux client:
import socket
s = socket.socket()
s.connect('192.168.1.1', 8080)
This hangs until timeout, as with the curl.
I believe the problem is due to your address binding. Python does not allow sockets bound to localhost (or 0.0.0.0) to be visible from the outside world. Change the binding to your actual IP Address.
EDIT: Showing example code
Change your code to this
import socket
s = socket.socket()
s.bind(('192.168.1.1', 8080)) # assumes your machine's IP address is 192.168.1.1
s.listen(1)
remotesock, addr = s.accept()

Categories