Python Sockets Port forwarding - python

So I port forwarded my ip so that my friends can test if my stuff works
And I have a simple server that is hosted on the internal ip
import socket
import threading
class Server:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
connections = []
def __init__(self, ip="0.0.0.0", port=5555):
self.sock.bind((ip, port))
self.sock.listen(1)
def handler(self, c, a):
while True:
data = c.recv(4096)
for connection in self.connections:
connection.send(data)
if not data:
print(str(a[0]) + ":" + str(a[1]), "disconnected")
self.connections.remove(c)
c.close()
break
def run(self):
while True:
c, a = self.sock.accept()
rThread = threading.Thread(target=self.handler, args=(c, a))
rThread.daemon = True
rThread.start()
self.connections.append(c)
print(str(a[0]) + ":" + str(a[1]), "connected")
host = Server("192.168.x.xxx", 6667)
print("Server status: Running")
host.run()
And a simple client module that I attempted to pass the public ip to
import socket
import pickle
import threading
import pyaudio
import numpy as np
class Client():
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
def __init__(self, address):
threading.Thread.__init__(self)
self.sock.connect((address, 6667))
def run(self, id):
RATE = 16000
CHUNK = 256
self.id = id
p = pyaudio.PyAudio()
player = p.open(format=pyaudio.paInt16, channels=1, rate=RATE, output=True, frames_per_buffer=CHUNK)
while True:
data = self.sock.recv(4096)
data = pickle.loads(data)
if data[0] != self.id:
if not data:
break
player.write(np.fromstring(data[1],dtype=np.int16),CHUNK)
def sendMsg(self, data, id):
data1 = [id, data]
self.sock.send(pickle.dumps(data1))
The client does not connect to the server when I try to give it the public address
print("Connecting to server")
cli = Client("91.242.xxx.xxx")
rThread = threading.Thread(target=cli.run, args=(id,))
rThread.daemon = True
rThread.start()
print("Connected to server")
The only thing that outputs is Connecting to server
I am not sure what I am doing wrong or what to do to fix this

My ISP uses CGNat and I just had to call them to tell them that I need a public IP and they gladly did it for me.

Related

ECONNABORTED when attempting to connect ESP32 and ESP8266

I'm attempting to connect an ESP32 and ESP8266 via sockets with micropython. I cannot get the ESP8266 client to connect to the ESP32 server without throwing an ECONNABORTED 103 error. Code is below, not sure what I'm doing wrong here. This seems to work when working off of my laptop and had no issues until trying to connect these two specific devies.
ESP32 Server Code:
import network
import socket
from time import sleep
SSID = 'esp'
KEY = 'meow'
ADDR = '192.168.4.1'
PORT = 2000
class socket_master:
def __init__(self):
self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.sock.bind(('',PORT))
self.attempt = 0
def accept_connection(self):
self.sock.listen(4)
self.conn, self.addr = self.sock.accept()
def test_speed(self):
data = 'attempt ' + str(self.attempt)
self.conn.sendall(data.encode())
self.attempt += 1
attempt = 0
try:
print('starting network')
ap = network.WLAN(network.AP_IF)
print('network started')
if ap.active() == False:
ap.active(True)
sleep(1)
ap.config(essid='esp')
print(ap.config('essid'))
print('set ssid')
print(ap.ifconfig())
except:
print('failed')
sm = socket_master()
sm.accept_connection()
print('waiting for client')
while True:
sm.test_speed()
ESP8266 Client Code:
# main.py -- put your code here!
import network
import socket
SSID = 'esp'
KEY = 'meow'
ADDR = '192.168.4.1'
PORT = 2000
def do_connect():
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
if not wlan.isconnected():
print('connecting to network...')
wlan.connect('esp')
while not wlan.isconnected():
pass
print('network config:', wlan.ifconfig())
class socket_master_2:
def __init__(self):
self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.sock.connect((ADDR,PORT))
def receive_print(self):
data = self.sock.recv(1024)
print(data)
print(data.decode())
do_connect()
client = socket_master_2()
while True:
client.receive_print()

How to handle client shutdown using threads in python?

I am new to Socket programming, My use case is to add shutdown message in my code that if one of the clients goes off or interrupted or killed then my server easily update the count or kill that thread.
import socket
import SSL
import testThread
context = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH)
context.verify_mode = ssl.CERT_REQUIRED
context.load_cert_chain(certfile=self.server_cert, keyfile=self.server_key)
context.load_verify_locations(cafile=self.ca_cert)
# to add threads
t = []
# to store addresses
totalAddress = []
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind((self.TCP_IP, self.TCP_Port))
s.listen(4)
while True:
print "Waiting for connections from TCP clients..."
(conn, (ip, port)) = tcpServer.accept()
print("Client connected: {}:{}".format(ip, port))
conn = context.wrap_socket(conn, server_side=True)
newthread = testThread.TestThread(ip, port, conn)
newthread.start()
t.append(newthread)
totalAddress.append((ip,port))
count = newthread.count() -1
print "[ACTIVE CONNECTIONS] {} and number of clients running {}".format(totalAddress, count)
I have created count() in testThread.py file.
import threading
from datetime import datetime
import time
class TestThread(Thread):
def __init__(self, ip, port, conn):
# import pdb; pdb.set_trace()
Thread.__init__(self)
self.ip = ip
self.port = port
self.conn = conn
print "[+] New server socket thread started for " + ip + ":" + str(port)
")
def run(self):
while True:
data = self.conn.recv(2048)
now = datetime.now()
data = str(now) + " - " + data
#print "Server received data:", data
f = open("demofile.txt", "a")
f.write(data)
f.close()
Please excuse me if there is an error in the code. :)

Why does the game's connection to the proxy server connection time-out?

I'm writing a TCP proxy server for Minecraft In python.
But when I run the program and try to connect to the proxy it just says that it is connecting and then
eventually times out
I am running the Minecraft server I am testing with as well as the proxy on my computer
the server on port 25565
the proxy on port 8080
although I have tested it on mineplex and hypixel as well
and it did not work on them either
How can I fix the issue
The code:
import socket
from threading import Thread
class Proxy2Server(Thread):
def __init__(self, host, port):
self.game = None
self.port = port
self.host = host
self.server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.server.connect((host, port))
def run(self):
while True:
data = self.server.recv(4096)
print("[server]", data)
if data:
self.game.sendall(data)
class Game2Proxy(Thread):
def __init__(self, host, port):
self.server = None
self.port = port
self.host = host
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
sock.bind((host, port))
sock.listen(1)
self.game, addr = sock.accept()
def run(self):
while True:
data = self.game.recv(4096)
print("[client]", data)
if data:
self.server.sendall(data)
class Proxy(Thread):
def __init__(self, from_host, to_host, from_port, to_port):
super(Proxy, self).__init__()
self.from_host = from_host
self.to_host = to_host
self.from_port = from_port
self.to_port = to_port
def run(self):
while True:
print(f"[proxy {self.from_host}:{self.from_port}] setting up")
self.g2p = Game2Proxy(self.from_host, self.from_port)
self.p2s = Proxy2Server(self.to_host, self.to_port)
print(f"[proxy {self.from_host}:{self.from_port}] connection established")
self.g2p.server = self.p2s.server
self.p2s.game = self.g2p.game
from_host = input("from-host$ ")
from_port = int(input("from-port$ "))
to_host = input("to-host$ ")
to_port = int(input("port$ "))
ProxyServer = Proxy(from_host, to_host, from_port, to_port)
ProxyServer.start()```

Python Socket Program - NameError: name 'self' is not defined. I changed the localhost, ports etc but this error refuses to go away

import socket
MAX_BUFFER_SIZE = 4096
class ClientSocket:
def __init__(self):
print("Client socket started....")
self.soc = None
def send_to_Server(self, data):
print('Time to send data to Server..... %s', data)
self.soc.send(data.encode("utf8"))
def receive_from_Server(self):
print('Time to receive from Server.....')
result_bytes = self.soc.recv(MAX_BUFFER_SIZE)
result_string = result_bytes.decode("utf8")
print("Result from server is {}".format(result_string))
def start_client(self):
self.soc = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.soc.connect(("localhost", 8000))
print('Client connected....')
husainshoab#hs-Len:~$ python IOTDeviceSocket.py
Traceback (most recent call last):
File "IOTDeviceSocket.py", line 7, in
class ClientSocket:
File "IOTDeviceSocket.py", line 11, in ClientSocket
self.soc = None
NameError: name 'self' is not defined
There appears to be nothing wrong with your code. I just used it to create a simple test application
# ClientSocket.py
import socket
MAX_BUFFER_SIZE = 4096
class ClientSocket:
def __init__(self):
print("Client socket started....")
self.soc = None
def send_to_Server(self, data):
print('Time to send data to Server..... %s', data)
self.soc.send(data.encode("utf8"))
def receive_from_Server(self):
print('Time to receive from Server.....')
result_bytes = self.soc.recv(MAX_BUFFER_SIZE)
result_string = result_bytes.decode("utf8")
print("Result from server is {}".format(result_string))
def start_client(self):
self.soc = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.soc.connect(("localhost", 8000))
print('Client connected....')
cs = ClientSocket()
cs.start_client()
cs.send_to_Server('Hello')
cs.receive_from_Server()
here's a simple test server which just spits back some JSON data
# test_server.py
import socket
from datetime import datetime
import json
def logMessage(clientMessage):
logTime = datetime.today();
msg = "{} | {}\n".format(logTime, clientMessage)
print msg
TCP_PORT = 8000
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind(('localhost', TCP_PORT))
# listen() puts the socket into server mode,
server.listen(1)
while True:
# wait for an incoming connection
connection, address = server.accept()
try:
# receive data in chunks of 64 bytes
while True:
data = connection.recv(64)
# how do we know if we received all the data?
if data:
# we received data from the client, log it to the file
logMessage(data)
response = {
'name' : 'Jonathan Swift',
'occupation' : 'author'
}
jsonResponse = json.dumps(response)
messageLength = len(jsonResponse)
bytesSent = 0
# send a response to the client after turning our dict into
# a JSON string
while(bytesSent < messageLength):
sent = connection.send(jsonResponse)
bytesSent += sent
else:
# no data, break out of receiving loop
break
except Exception as e:
raise
finally:
connection.close()
import socket
MAX_BUFFER_SIZE = 4096
class ClientSocket:
soc = None
def __init__(self):
print("Client socket started....")
self.soc = None
def send_to_Server(self, data):
print('Time to send data to Server..... %s', data)
self.soc.send(data.encode("utf8"))
def receive_from_Server(self):
print('Time to receive from Server.....')
result_bytes = self.soc.recv(MAX_BUFFER_SIZE)
result_string = result_bytes.decode("utf8")
print("Result from server is {}".format(result_string))
def start_client(self):
self.soc = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.soc.connect(("localhost", 8000))
print('Client connected....')
you should define the soc variable after class statement so that you can use it globally.

Manipulating socketstream in Python

I'm trying to create a small, multithreaded proxyscript that allows me to proxy LDAP requests and manipulate the results (like adding extra fields, renaming them etc).
In the example below, I try to replace the field 'TEST' by 'DONE'. Is there any solution to allow this socketstream to be manipulated? Should I decode it somewhat first?
import select
import socket
import sys
import threading
import signal
import re
import random
import time
import binascii
from ldaptor.protocols import pureldap, pureber
from time import gmtime, strftime
ASTLDAP_PROXY_PORT = 1389
ASTLDAP_HOST = 'localhost'
ASTLDAP_PORT = 389
BUFFERSIZE = 1024
DELAY = 0.0001
class Forward:
def __init__(self):
self.forward = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
def start(self, host, port):
try:
self.forward.connect((host, port))
return self.forward
except Exception, e:
print e
return False
class AstLdapProxyServer(threading.Thread):
input_list = []
channel = {}
def __init__(self, host, port, socket):
threading.Thread.__init__(self)
self.host = host
self.port = port
# Socket ontvangen die we meekregen bij nieuwe thread.
self.socket = socket
print "[+] New thread started for "+host+":"+str(port)
self.socket.bind((host, port))
self.socket.listen(200)
def register_signals(self):
signal.signal(signal.SIGHUP, self.signal_handler)
signal.signal(signal.SIGINT, self.signal_handler)
signal.signal(signal.SIGQUIT, self.signal_handler)
def main_loop(self):
self.input_list.append(self.socket)
while 1:
#time.sleep(DELAY)
ss = select.select
inputready, outputready, exceptready = ss(self.input_list, [], [])
for self.s in inputready:
if self.s == self.socket:
self.on_accept()
break
self.data = self.s.recv(BUFFERSIZE)
if len(self.data) == 0:
self.on_close()
else:
self.on_recv()
def on_accept(self):
forward = Forward().start(ASTLDAP_HOST, ASTLDAP_PORT)
clientsock, clientaddr = self.socket.accept()
if forward:
print clientaddr, "has connected"
self.input_list.append(clientsock)
self.input_list.append(forward)
self.channel[clientsock] = forward
self.channel[forward] = clientsock
else:
print "Can't establish connection with remote server.",
print "Closing connection with client side", clientaddr
clientsock.close()
def on_close(self):
print self.s.getpeername(), "has disconnected"
#remove objects from input_list
self.input_list.remove(self.s)
self.input_list.remove(self.channel[self.s])
out = self.channel[self.s]
# close the connection with client
self.channel[out].close() # equivalent to do self.s.close()
# close the connection with remote server
self.channel[self.s].close()
# delete both objects from channel dict
del self.channel[out]
del self.channel[self.s]
def on_recv(self):
data = self.data
# Manipulate result
output = re.sub(r'uzgEmail1', r'TEST', data)
# Send result to client (DOESN'T WORK)
self.channel[self.s].send(output)
# Send result to client (WORKS when I disable send above)
self.channel[self.s].send(data)
if __name__ == '__main__':
tcpsock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
tcpsock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
tcpsock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
server = AstLdapProxyServer(ASTLDAP_HOST, ASTLDAP_PROXY_PORT, tcpsock)
server.start()
try:
server.main_loop()
except KeyboardInterrupt:
sys.exit(1)

Categories