pymongo basic functions not working [duplicate] - mongodb

I was following a tutorial called "Black Hat Python" and got a "the requested address is not valid in its context" error. I'm Python IDE version: 2.7.12
This is my code:
import socket
import threading
bind_ip = "184.168.237.1"
bind_port = 21
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind((bind_ip,bind_port))
server.listen(5)
print "[*] Listening on %s:%d" % (bind_ip,bind_port)
def handle_client(client_socket):
request = client_socket.rev(1024)
print "[*] Recieved: %s" % request
client_socket.close()
while True:
client,addr = server.accept()
print "[*] Accepted connection from: %s:%d" % (addr[0],addr[1])
client_handler = threading.Thread(target=handle_client,args=(client,))
client_handler.start()
and this is my error:
Traceback (most recent call last):
File "C:/Python34/learning hacking.py", line 9, in <module>
server.bind((bind_ip,bind_port))
File "C:\Python27\lib\socket.py", line 228, in meth
return getattr(self._sock,name)(*args)
error: [Errno 10049] The requested address is not valid in its context
>>>

You are trying to bind to an IP address that is not actually assigned to your network interface:
bind_ip = "184.168.237.1"
See the Windows Sockets Error Codes documentation:
WSAEADDRNOTAVAIL 10049
Cannot assign requested address.
The requested address is not valid in its context. This normally results from an attempt to bind to an address that is not valid for the local computer.
That may be an IP address that your router is listening to before using NAT (network address translation) to talk to your computer, but that doesn't mean your computer sees that IP address at all.
Either bind to 0.0.0.0, which will use all available IP addresses (both localhost and any public addresses configured):
bind_ip = "0.0.0.0"
or use any address that your computer is configured for; run ipconfig /all in a console to see your network configuration.
You probably also don't want to use ports < 1024; those are reserved for processes running as root only. You'll have to pick a higher number than that if you want to run an unprivileged process (and in the majority of tutorials programs, that is exactly what you want):
port = 5021 # arbitrary port number higher than 1023
I believe the specific tutorial you are following uses BIND_IP = '0.0.0.0' and BIND_PORT = 9090.

I was just getting this error while following this Python TCP example and the solution was to have my client connect using 'localhost' instead of '0.0.0.0'.

Related

Unable to establish connection to a tcp socket server on aws ec2

I am trying to run a socket server on an aws ec2 ubuntu instance and then connecting with it using my local machine. I was successful with sending HTTP GET requests to my server hosted on aws ec2 instance and getting a response, but I am unable to connect the server and client using sockets, even after enabling custom TCP on the complete range of ports on the instance.
Here is a screenshot describing my instance's inbound and outbound rules :
screenshot
I used this python code from the internet to test socket networking :
socket_client.py :
import socket
def client_program():
host = "<aws instance public ip address>"
port = 8080 # socket server port number
client_socket = socket.socket() # instantiate
client_socket.connect((host, port)) # connect to the server
message = input(" -> ") # take input
while message.lower().strip() != 'bye':
client_socket.send(message.encode()) # send message
data = client_socket.recv(1024).decode() # receive response
print('Received from server: ' + data) # show in terminal
message = input(" -> ") # again take input
client_socket.close() # close the connection
if __name__ == '__main__':
client_program()
socket_server.py :
import socket
def server_program():
host = "0.0.0.0"
port = 8080 # initiate port no above 1024
server_socket = socket.socket() # get instance
# look closely. The bind() function takes tuple as argument
server_socket.bind((host, port)) # bind host address and port together
# configure how many client the server can listen simultaneously
server_socket.listen(2)
conn, address = server_socket.accept() # accept new connection
print("Connection from: " + str(address))
while True:
# receive data stream. it won't accept data packet greater than 1024 bytes
data = conn.recv(1024).decode()
if not data:
# if data is not received break
break
print("from connected user: " + str(data))
data = input(' -> ')
conn.send(data.encode()) # send data to the client
conn.close() # close the connection
if __name__ == '__main__':
server_program()
Note that the socket server-client are working completely fine when run on my local machine.
Please help if you know about how to fix this .
Edit - I have also tried with disabling firewall on the linux ec2 instance, but the problem still persists.
Thanks.

Expose mongodb using cloudflare zero trust tunnels and connect via pymongo

Hi I am currently trying to set up a mongo db on my home server and expose it to the internet using cloudflare tunnels.
I have a service up and running and have the following for the connection.
client = MongoClient('<DATABASE_URL>')
I get this error...
pymongo.errors.InvalidURI: Invalid URI scheme: URI must begin with 'mongodb://' or 'mongodb+srv://'
I am tunneling the default ip that mongo gives you.
UPDATE
I tested connecting to the db and just printing the database to the console. I got this result
Database(MongoClient(host=['<my_domain>:27107'], document_class=dict, tz_aware=False, connect=True), 'test_db')
I assume that because it says "connect=true" that means it is connecting to the database now.
I tried to add a collection to the database using an example I got online and this is the error I received...
Traceback (most recent call last):
File "/home/michael/mongo.py", line 18, in <module>
x = mycol.insert_one(mydict)
File "/home/michael/anaconda3/lib/python3.9/site-packages/pymongo/collection.py", line 628, in insert_one
self._insert_one(
File "/home/michael/anaconda3/lib/python3.9/site-packages/pymongo/collection.py", line 569, in _insert_one
self.__database.client._retryable_write(acknowledged, _insert_command, session)
File "/home/michael/anaconda3/lib/python3.9/site-packages/pymongo/mongo_client.py", line 1475, in _retryable_write
with self._tmp_session(session) as s:
File "/home/michael/anaconda3/lib/python3.9/contextlib.py", line 119, in __enter__
return next(self.gen)
File "/home/michael/anaconda3/lib/python3.9/site-packages/pymongo/mongo_client.py", line 1757, in _tmp_session
s = self._ensure_session(session)
File "/home/michael/anaconda3/lib/python3.9/site-packages/pymongo/mongo_client.py", line 1740, in _ensure_session
return self.__start_session(True, causal_consistency=False)
File "/home/michael/anaconda3/lib/python3.9/site-packages/pymongo/mongo_client.py", line 1685, in __start_session
self._topology._check_implicit_session_support()
File "/home/michael/anaconda3/lib/python3.9/site-packages/pymongo/topology.py", line 538, in _check_implicit_session_support
self._check_session_support()
File "/home/michael/anaconda3/lib/python3.9/site-packages/pymongo/topology.py", line 554, in _check_session_support
self._select_servers_loop(
File "/home/michael/anaconda3/lib/python3.9/site-packages/pymongo/topology.py", line 238, in _select_servers_loop
raise ServerSelectionTimeoutError(
pymongo.errors.ServerSelectionTimeoutError: No servers found yet, Timeout: 30s, Topology Description: <TopologyDescription id: 63d172246419f5effc5e32d3, topology_type: Unknown, servers: [<ServerDescription ('<my_domain>', 27107) server_type: Unknown, rtt: None>]>
For reference this is what my pymongo test file looks like.
mongo.py
import pymongo
con = pymongo.MongoClient("mongodb://<my_domain>:27107")
db = con["test_db"]
mycol = db["customers"]
print(mycol)
print(db)
mydict = { "name": "John", "address": "Highway 37" }
x = mycol.insert_one(mydict)
If it's a standard installation, you need to make sure cloudflare tunnel is exposing port 27017. The ingress rule must be:
tcp://localhost:27017
To connect, just use:
pymongo.MongoClient("mongodb://user:psw#host.YourTLD/table")
It's a good idea to activate authentication if you're exposing the whole server to the internet. You can do it by setting authentication on the mongodb server, or at the cloudflare zero trust edge following this guide:
https://developers.cloudflare.com/cloudflare-one/tutorials/mongodb-tunnel/
I guess this is the case here:
you have a locally deployed mongodb (not some external VM)
you've set a Cloudflare tunnel in order to expose mongodb over dns
and you are having problems to connect to mongodb using that dns
So I've recently been trying to do the same, and I got over it with these steps:
First off, make sure that your service type, in Cloudflare Zero Trust, is TCP
URL is probably localhost, make sure you specified port
download cloudflared: Apple Silicon & everything else probably
run this on your local machine that you want to connect from: cloudflared access tcp --hostname <hostname you've set on Cloudflare ZT> --url <url you want to be forwarded to>. For example: cloudflared access tcp --hostname mongo.example.com --url localhost:3000
Then try to connect with your app to the localhost:3000.
How does this work?
Well, first you install cloudflared service, which forwards encrypted connection from an app on your machine to the outer internet.
You can protect access to that forwarded service/app using access rules. I also recommend protecting your app/service, you can do it from MongoDB or Cloudflare ZT, or both.
Then, you run cloudflared app on your target machine
connect to Cloudflare servers which forwards your MongoDB instance connection to the specified port on your local machine
you can access it as its local deployment

Flutter / Dart Error SocketException: OS Error: The remote computer refused the network connection. , errno = 1225, address = 127.0.0.1, port = 59250

I am getting this error in my debugger.
From what I understood it's an error generated by ip config.
I found this solve here, but i dont understand where should i modify it. where should i change the ip address?
Flutter SocketException (SocketException: OS Error: Connection refused, errno = 111, address = localhost, port = 51500)
ERROR - 2021-03-23 18:21:26.074284
PUT /SXUs66yGd7s=/
Error thrown by handler.
SocketException: OS Error: The remote computer refused the network connection.
, errno = 1225, address = 127.0.0.1, port = 59250
Help!
Thank you alot
I was going through this trouble myself
i just disconnect the emulator and restated
Not sure what is your environment:
for me->
I tried to run windows app with xampp localhost and received this error.
then i changed my uri in frontend to
String uri = 'http://127.0.0.1/db-name';
after that, all working.
in the emulator the uri is different.
String uri = 'http://your ip addres/db-name';
to get your ip address->
open cmd and run "ipconfig"
use ipv4.

LibGDX: Error making a socket connection to *ip-adress*

I want to make 2 devices communicate via sockets.
I use this code for the client socket:
Socket socket = Gdx.net.newClientSocket(Net.Protocol.TCP, adress, 1337, socketHints);
(SocketHints: timeout = 4000)
I get a GdxRuntimeException each time this line is being executed. What is wrong with the socket?
Screenshot of stack trace
You get that message because the socket couldn't be opened.
Note the last line about the return in the API:
newClientSocket:
Socket newClientSocket(Net.Protocol protocol,
java.lang.String host,
int port,
SocketHints hints)
Creates a new TCP client socket that connects to the given host and port.
Parameters:
host - the host address
port - the port
hints - additional SocketHints used to create the socket. Input null to use the default setting provided by the system.
Returns:
GdxRuntimeException in case the socket couldn't be opened
Try doing some debugging to find out why you are getting this error.
Is the port already in use? Are you trying to open more than one connection on the same port? Is the server IP valid? Maybe something else is causing the issue?

Python Server Client WinError 10057

I'm making a server and client in Python 3.3 using the socket module. My server code is working fine, but this client code is returning an error. Here's the code:
import socket
import sys
import os
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
server_address = ('192.168.1.5', 4242)
sock.bind(server_address)
while True:
command = sock.recv(1024)
try:
os.system(command)
sock.send("yes")
except:
sock.send("no")
And here's the error:
Error in line: command = sock.recv(1024)
OSError: [WinError 10057] A request to send or receive data was disallowed because the socket is not connected and (when sending on a datagram socket using a sendto call) no address was supplied
What on earth is going on?
It looks like you're confused about when you actually connect to the server, so just remember that you always bind to a local port first. Therefore, this line:
server_address = ('192.168.1.5', 4242)
Should actually read:
server_address = ('', 4242)
Then, before your infinite loop, put in the following line of code:
sock.connect(('192.168.1.5', 4242))
And you should be good to go. Good luck!
EDIT: I suppose I should be more careful with the term "always." In this case, you want to bind to a local socket first.
You didn't accept any requests, and you can only recv and/or send on the accepted socket in order to communicate with client.
Does your server only need one client to be connected? If so, try this solution:
Try adding the following before the while loop
sock.listen(1) # 1 Pending connections at most
client=sock.accept() # Accept a connection request
In the while loop, you need to change all sock to client because server socket cannot
be either written or read (all it does is listening at 192.168.1.5:4242).