I have a python network server code.
import socket
HOST, PORT = '', 5000
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)
http_response = """\
HTTP/1.1 200 OK
Content-Type: text/html; charset=utf-8
<H1>Hello, World!</H1>
"""
client_connection.sendall(http_response.encode())
client_connection.close()
I have a client code that accesses the server.
import socket
HOST = '127.0.0.1'
PORT = 5000 # The port used by the server
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print "Socket successfully created"
s.connect((HOST, PORT))
s.sendall('GET /')
data = s.recv(1000)
print('Received', repr(data))
s.close
except socket.error as err:
print "socket creation failed with error %s" %(err)
It works fine with the expected output when I executed the server and client.
Socket successfully created
('Received', "'HTTP/1.1 200 OK\\nContent-Type: text/html; charset=utf-8\\n\\n<H1>Hello, World!</H1>\\n'")
Then, I tried to execute the python server using ngrok.
Session Status online
Account ...
Version 2.3.34
Region United States (us)
Web Interface http://127.0.0.1:4040
Forwarding http://d2fccf7f.ngrok.io -> http://localhost:5000
Using curl, I could access the webserver with ngrok.
> curl http://d2fccf7f.ngrok.io
<H1>Hello, World!</H1>
However, when I tried to use the same client code with minor modifications, the server doesn't seem to respond.
import socket
ip = socket.gethostbyname('d2fccf7f.ngrok.io')
print(ip)
HOST = ip
PORT = 5000
# the rest of the code is the same
I changed the PORT to 80 or 8080, but I had same results.
What might be wrong?
Might I suggest trying something like pyngrok to programmatically manage your ngrok tunnel for you? Full disclosure, I am the developer of it. Socket and other TCP examples are here.
From oguz ismail's hint, I made the following REQUEST header to make it work. I see that the Host information and blank line should be required.
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print "Socket successfully created"
s.connect((HOST, PORT))
header = '''GET / HTTP/1.1\r\nHost: d2fccf7f.ngrok.io\r\n\r\n'''
...
Related
I'm trying to make basic synchronous hello world with sockets
(server is supposed to send some message as answer for any message from client).
I bind localhost:5000 to socket
I'm trying to receive console input with sock.recv(4096)
I try to connect to socket from the console using curl localhost:5000, but I can't write to the console. Also, server sends message when i connect to it, but nothing more
here is the code:
import socket
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
server_socket.bind(("localhost", 5000))
server_socket.listen()
def accept_connection(server_socket):
while True:
client_socket, addr = server_socket.accept()
print("connection from", addr)
send_message(client_socket)
def send_message(client_socket):
while True:
request = client_socket.recv(4096)
if request:
response = "request recieved\n".encode()
client_socket.send(response)
else:
break
print("done with sending stuff")
client_socket.close()
if __name__ == "__main__":
print("stuff_started")
accept_connection(server_socket)
server output:
C:\Users\USER\Desktop\stuff\pth>python testing.py
stuff_started
connection from ('127.0.0.1', 53053)
client output:
C:\Users\USER\Desktop\stuff\pth>curl localhost:5000
request recieved
As written in the comments, curl is used to HTTP servers and not for generic sockets.
You can use netcat for that:
nc 127.0.0.1 5000
or just plain old Python in your favorite shell like so:
> py -c "import socket; s = socket.create_connection(('localhost', 5000)); s.sendall(b'data'); print(s.recv(1024))"
b'request recieved\n'
I have a simple server-client combo running on 2 computers in 2 different networks. The server (a Raspberry) has a TCP tunnel running.
Now running on the code on localhost is fine, on 2 different machines with correct IP and port (I can ping the server via telnet and establish connection via ssh using the same IP and port), I just get the following on the client side AND NOTHING ELSE:
Received SSH-2.0-OpenSSH_7.9p1 Raspbian-10+deb10u2
I should instead receive: Received b'Hello, world'
On the serverside I receive no message at all.
What do I need to run it in 2 different networks? Below the source codes.
server.py:
#!/usr/bin/env python3
import socket
HOST = '' # Standard loopback interface address (localhost)
PORT = 65432 # Port to listen on (non-privileged ports are > 1023)
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.bind((HOST, PORT))
s.listen()
conn, addr = s.accept()
with conn:
print("Connected by", addr)
while True:
data = conn.recv(1024)
if not data:
break
conn.sendall(data)
client.py:
#!/usr/bin/env python3
import socket
HOST = 'xxx.xxx.xxx.xxx' # The server's hostname or GLOBAL IP address
PORT = 12345 # The port used by the server, not actually 12345
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.connect((HOST, PORT))
s.sendall(b"Hello, world")
data = s.recv(1024)
print("Received", repr(data))
I know this was already asked but the previous questions didn't help. I'm trying to send some data using sockets. Specifically I'm using my laptop as server and a Linux emulator (Termux) on my smartphone as a client. Here below you can see the two Python codes. For the server:
import socket
HOST = ''
PORT = 5555
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((HOST, PORT))
s.listen()
conn, addr = s.accept()
print('Connected by', addr)
while True:
data = conn.recv(1024)
if not data:
break
conn.sendall(data)
s.close()
And for the client:
import socket
HOST = ''
PORT = 5555
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((HOST, PORT))
s.sendall(b'Hello, world')
data = s.recv(1024)
print('Received', repr(data))
s.close()
When I'm connected to the same WiFi and in HOST (in both codes) I put the IP I see from ipconfig (192.168.---.---) everything works. It also works if in the HOST of the server I put 0.0.0.0.
However, when I put the IP of the machine (that I can see on https://whatismyipaddress.com/) and instead of using the WiFi I use the phone connection I get: ConnectionRefusedError: [Errno 111] Connection Refused.
Can someone explain me how can I connect client and server when the networks are different? I have been stuck with this for a while.
I also tried to open a port on the Firewall following this procedure and put it in the code instead of 5555 but still it didn't work.
Thank you in advance for the help.
I am trying to create a client to connect to a server with given url address.
I used this way
host_ip = socket.gethostbyname('HOST_NAME')
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.bind(('127.0.0.1', 0))
sock.connect((host_ip, 8080))
but it printed the following error
OSError: [Errno 22] Invalid argument
Can someone explain me why is wrong and give me a solution?
You don't have to bind your socket, this is done server-side.
Here's the example code from the documentation for socket :
import socket
HOST = 'your-url.net' # The remote host
PORT = 8080 # The same port as used by the server
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.connect((HOST, PORT))
s.sendall(b'Hello, world')
data = s.recv(1024)
print('Received', repr(data))
This is a simple snippet, which connects to the server, sends some data, and prints the response.
I'm writing a TCP python script that will act as a server and retrieve a temperature reading from a machine (the client). I need to pass a command to the client from the server and listen for an output of the response. I successfully reach the cmd definition line, but when s.accept() is called I'm left hanging with no response from the client.
Server.py
import socket
port = 7777
ip = raw_input('192.168.62.233')
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((ip, port))
s.listen(1)
print "waiting on port: ", port
while True:
cmd = raw_input('KRDG? A[term]')#command send to client
conn, addr = s.accept()
s.send(cmd)
print "It sent"
data = conn.recv(4096)
print "Received:", data, " from address ", addr
Edit:
I believe you're correct, I should consider my code the client and temperature readout at the server. I do now get left hanging after "here 2" when I go to s.recv().
Client.py
import socket
ip = '192.168.62.233'
port = 7777 # The same port as used by the server
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((ip, port))
print 'here'
s.send('KRDG? A[term]')
print 'here 2'
data = s.recv(4096)
print 'here 3'
s.close()
print 'Received', repr(data)
Usually, a TCP server accept will block while it waits for a client to connect. Have you checked to make sure that you client can and is connecting? You could use a tool like tcpdump or similar to watch the network activity and make sure the client is connecting.