Socket doesn't communicate with other networks - python

Im trying to send a 8 digit pin code from one computer to another, the code works when both of the computers are on the same networks.But there seems to be a problem when they are not on the same network. it just doesnt send the pin to the server pc.
receives the data from the client and saves it
server.py
import socket
import json
import Classes
def recive_pin(s_data):
pin = s_data.recv(int(s_data.recv(1).decode())).decode()
return pin
def main():
# gets port from json file
with open("Config.JSON", 'r') as f:
json_data = json.load(f)
port = json_data["load"]["port"]
# create the tcp socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# binds the socket to localhost , config port number
ip = '0.0.0.0'
s.bind((ip, port))
user_data = {}
while 1:
s.listen()
s_data, address = s.accept()
command = s_data.recv(1).decode()
if command == "P":
user_data[recive_pin(s_data)] = address
print(user_data)
if __name__ == '__main__':
main()
client.py
create a 8 digit code and sends it to the server
import socket
import json
import Classes
def main():
# gets the user input controlled/controller.
with open("Config.JSON", 'r') as f:
json_data = json.load(f)
port = json_data["load"]["port"]
ip = json_data["load"]["ip"]
c = Classes.handler(ip, port)
x = Classes.pin.create_pin()
c.send_pin(x)
if __name__ == '__main__':
main()
Classes.py
import random
import string
import socket
class handler:
def __init__(self, comunication_ip=0, port=0, ):
self.__comunication_ip = comunication_ip
self.__port = int(port)
# type of command to send to the server
# tuple of the server details
self.__server_details = (self.__comunication_ip, self.__port)
def send_pin(self, verification_pin):
# command type : Send_pin("P")
command_type = "P"
# creates a socket to send the pin to the server
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# adds the type of the command and the length of the pin to the Pin.
msg = command_type + str(len(verification_pin)) + verification_pin
s.connect(self.__server_details)
s.send(msg.encode())
class pin:
#staticmethod
# def __init__(self, defult_pin=0):
# self.__pin = defult_pin
def create_pin():
characters = string.ascii_letters + string.digits + string.punctuation
verification_pin = str(''.join(random.choice(characters) for length in range(8)))
return str(verification_pin)
i also use a Json file to save the port number and the server ip :
{
"load":{
"ip":"10.100.102.94",
"port": 12000
}
}

Related

Python how to use string in multiple scripts

I'm running a python script on a raspberry pi that reads keyboard input to a string and will be sending that string through TCP. I've made two script one that reads the input and one that can send the string if needed. How can i use one string and use it in both scripts for readings and writings?
I've used an text document. Only becaue of the sd card i wanne achieve an connecting between the two scripts
Reading part:
#loops for Barcode_Data
def Create_File():
file = open("Barcode_data.txt", "w")
file.write(" // ")
file.close()
empty = ''
def Barcode_Read():
Barcode_Data= input("Input: ",)
print(Barcode_Data)
file = open("Barcode_data.txt", "a")
file.write(Barcode_Data)
file.write(" // ")
file.close()
#Loop that will only run once
Create_File()
#Loop that will run continuesly
while True:
Barcode_Read()
TCP Server:
#TCP server
def TCP_Connect(socket):
socket.listen()
conn, addr = socket.accept()
with conn:
data = conn.recv(1024)
if data == b'Barcode_Data':
tcp_file = open("Barcode_data.txt", "r")
Barcode_Data = tcp_file.read()
tcp_file.close()
conn.sendall(Barcode_Data.encode('utf-8'))
elif data == b'Clear Barcode_Data':
tcp_file = open("Barcode_data.txt", "w")
tcp_file.write(" // ")
tcp_file.close()
#TCP Socket setup
HOST = '' # Standard loopback interface address (localhost)
PORT = 1025 # Port to listen on (non-privileged ports are > 1023)
import socket
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.bind((HOST, PORT))
#Loop that wil run continuesly
while True:
TCP_Connect(s)
You can use the code from this question as is: Interprocess communication in Python
Server process:
from multiprocessing.connection import Listener
address = ('localhost', 6000) # family is deduced to be 'AF_INET'
listener = Listener(address, authkey='secret password')
conn = listener.accept()
print 'connection accepted from', listener.last_accepted
while True:
msg = conn.recv()
# do something with msg
if msg == 'close':
conn.close()
break
listener.close()
Client process:
from multiprocessing.connection import Client
address = ('localhost', 6000)
conn = Client(address, authkey='secret password')
conn.send('close')
# can also send arbitrary objects:
# conn.send(['a', 2.5, None, int, sum])
conn.close()
Documentation is available here: https://docs.python.org/3.7/library/multiprocessing.html#multiprocessing-listeners-clients

making TCP web Server with python

I have created a multi threaded python web server and it is working fine for my client server.However i want it to take results work for web server as well. Please help me understand how we do that
the server
import socket
import threading
import os
import sys
#to convert bytes into string
def bytestoString(stringToRead):
stringToRead = bytes.decode(stringToRead)
type(stringToRead)
return(stringToRead)
#to conver string into bytes
def stringToBytes(bytesToSend1):
bytesToSend1= str.encode(bytesToSend1)
type (bytes)
return(bytesToSend1)
#to retreive a file
def retrFile(name,sock):
fileName=sock.recv(1024)
fileName_string = bytestoString(fileName)
print(fileName_string)
stringLength=len(fileName)
fileName_string = bytestoString(fileName[4:(stringLength-8)])
if os.path.isfile(fileName_string):
fileSize=str(os.path.getsize(fileName_string))
fileSize_Bytes = stringToBytes(fileSize)
exists_Bytes=stringToBytes('HTTP/1.1 200 OK')
sock.send(exists_Bytes)
ContentLength_Bytes=stringToBytes('Content-Length:')
sock.send(ContentLength_Bytes+fileSize_Bytes)
userResponse=sock.recv(1024)
userResponse=bytestoString(userResponse)
if userResponse[:2]=='Y':
print ('Ready to send the file................')
with open(fileName_string,'rb') as fileRead:
data= fileRead.read(1024)
sock.send(data)
while data!="":
data=fileRead.read(1024)
sock.send(data)
fileRead.close()
print('xyz')
elif userResponse[:2]=='N':
print('User Terminated file download, Thanks for connecting')
else :
httpResponse=stringToBytes('HTTP/1.1 404 not Found')
sock.send(httpResponse)
sock.close()
def Main(serverPort):
#creating a server socket type TCP
serverSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
localHost=socket.gethostname()
#binding the server to the client
serverSocket.bind((localHost,serverPort))
serverSocket.listen(5)
print ('***Server is ready to recieve***')
while True:
connectionSocket, addr = serverSocket.accept()
print ('got connection from:<', addr,'>')
t=threading.Thread(target=retrFile,args=('retrThread',connectionSocket))
t.start()
connectionSocket.send('thank you for connecting')
connectionSocket.close()
if __name__ == '__main__':
#getting server hostname and port number from the user
serverPort=int(sys.argv[1])
Main(serverPort)
The Client
import sys
import socket
#to convert bytes into string
def bytestoString(stringToRead):
stringToRead = bytes.decode(stringToRead)
type(stringToRead)
return(stringToRead)
#to conver string into bytes
def stringToBytes(bytesToSend):
bytesToSend= str.encode(bytesToSend)
type (bytes)
return(bytesToSend)
#def header():
def Main(serverName,serverPort,fileName_bytes,fileName):
print('***Initialising the socket***')
serverAddress=(serverName,serverPort)
#create the TCP/IP socket using user inout for server and port
clientSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
clientSocket.connect(serverAddress)
httpFileRequest=('GET/'+fileName+' HTTP/1.0')
httpFileRequest=stringToBytes(httpFileRequest)
#Reading the Hostname,socket family, socket type, protocol for the server
connectionDetails= socket.getaddrinfo(serverName,serverPort)
#printing the values to the screen
print (connectionDetails)
#print('Family:',families)
#print('type:',types)
#print('protocol:',protocols)
#Sending the request to recieve the file from the server
if fileName_bytes!="q":
clientSocket.send(httpFileRequest)
serverResponse=clientSocket.recv(1024)
serverResponse_string = bytestoString(serverResponse)
print(serverResponse_string)
fileLength=clientSocket.recv(1024)
fileLength_string = bytestoString(fileLength)
print(fileLength_string)
#checking the server response and downloading the file
if serverResponse_string[13:15]=='OK':
fileSize= float(int(fileLength_string[15:17]))
print(('Size of file you wish to download is:'),fileSize)
clientChoice=input('Please Enter Your Choice (Y/N)?:')
if clientChoice=='Y':
clientChoice=stringToBytes(clientChoice)
clientSocket.send(clientChoice)
#recieveing the file from the server
file = open('new_'+fileName,'wb')
print ('file opened.............')
data=clientSocket.recv(1024)
totalRecv=float(len(data))
file.write(data)
while totalRecv<fileSize:
data=clientSocket.recv(1024)
totalRecv+=len(data)
file.write(data)
percentComplte=int(int((totalRecv)/int(fileSize)*100))
print (('we have completed'),percentComplte,('%'))
file.close()
print ('Download complete')
elif clientChoice=='N':
clientChoice=stringToBytes(clientChoice)
clientSocket.send(clientChoice)
print ('File download terminated')
else :
print ('Please enter the correct choice')
else:
print (serverResponse_string)
clientSocket.close()
#Getting Hostname,socket family, socket type, protocol for the server
def get_constants(prefix):
"""Create a dictionary mapping socket module constants to their names."""
return dict( (getattr(socket, n), n)
for n in dir(socket)
if n.startswith(prefix)
)
#calling main function
if __name__ == '__main__':
#getting server hostname and port number from the user
serverName=sys.argv[1]
serverPort=int(sys.argv[2])
fileName= str(sys.argv[3])
fileName_bytes = str.encode(fileName)
type(bytes)
Main(serverName,serverPort,fileName_bytes,fileName)

Sending strings from a list over a socket to be displayed in real time

My list contains IP addresses and port numbers of connected clients to my program. The admin threads role is to send each currently connected clients IP address and port number to an admin client in this string format - eg '172.0.0.1 1234'. Could I have some advise on how to send each each address so that it only shows currently connected addresses and port numbers on the admin client program.
addressList is a global variable list
Here is my code-
Server
import threading
import socket
import math
import random
import ssl
addressList = []
def within(guess,goal,n):
absValue = abs(guess - goal)
if absValue <= n:
return True
else:
return False
def HandleAdmin(adminSocket,):
global addressList
(c,a) = adminSocket.accept()
ts = ssl.wrap_socket(c, certfile="5cc515_server.crt",
keyfile="5cc515_server.key",
server_side=True,
cert_reqs=ssl.CERT_REQUIRED,
ca_certs="5cc515-root-ca.cer")
if ts.recv(80).decode() == 'Hello\r\n':
ts.send('Admin-Greetings\r\n'.encode())
if ts.recv(80).decode() == 'Who\r\n':
for addr in addressList:
ts.send(addr).encode()
ts.close()
return
def HandleClient(c,a):
global addressList
address, port = a
address = str(address) + ' ' + str(port)
addressList.append(address)
scoreCount = 0
guess = 0
if(c.recv(80).decode()) == 'Hello\r\n':
c.send('Greetings\r\n'.encode())
goal = random.randrange(1,21)
while guess!= goal:
guess =c.recv(80).decode()
guess = int(guess[7:len(guess)-2])
if guess == goal:
c.send('Correct\r\n'.encode())
elif within(guess, goal, 2) == True:
c.send('Close\r\n'.encode())
else:
c.send('Far\r\n'.encode())
c.close()
return
clientSocket = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
clientSocket.bind(("127.0.0.1",4000))
clientSocket.listen(5)
adminSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
adminSocket.bind(("127.0.0.1",4001))
adminSocket.listen(5)
handleAdminThread = threading.Thread(target = HandleAdmin,
args = (adminSocket,))
handleAdminThread.start()
while True:
(c,a) = clientSocket.accept()
clientThread = threading.Thread(target = HandleClient, args = (c,a))
clientThread.start()
Admin Client
import ssl
import socket
s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
ts = ssl.wrap_socket(s, certfile="100298750.crt",
keyfile="100298750.key",
ca_certs="5cc515-root-ca.cer")
ts.connect(('127.0.0.1', 4001))
ts.send("Hello\r\n".encode())
addressList = []
if ts.recv(80).decode() == "Admin-Greetings\r\n":
print("The players currently playing are:\n\n")
ts.send("Who\r\n".encode())
while True:
print(ts.recv(80).decode())
In your HandleClient function, c.close() means the client has disconnected.
So, to let your admin know they did, you have to remove that address from the 'addressList' (since when you send "Who\r\n" your addressList list is referred to).
So, after c.close() you should write:
addressList.remove(address)

python 3.4.3 file is not writing completly

The following is complete client , server and sendproc codes:
Client.py
from socket import *
import pickle
import sendproc
import struct
s = socket(AF_INET, SOCK_STREAM) # Create a socket object
host = "192.168.1.4" # Get local machine name
port = 1094 # Reserve a port for your service.
s.connect((host, port))
with open("file.txt",'rb') as f:
print ('file opened')
print('Sending file...')
for data in f:
print(data)
print("MSG sent")
sendproc.send_msg(s, data)
Server.py
from socket import *
import pickle
import sendproc
port = 1094 # Reserve port for service.
s = socket(AF_INET,SOCK_STREAM) # Create a socket object
host = "192.168.1.4" # Get local machine name
s.bind((host, port)) # Bind to the port
s.listen(5)
print('server is listening')
conn,addr = s.accept()
with open("file1.txt",'w') as fb:
print("File downloading\n",fb)
while True:
print("hi")
data = sendproc.recv_msg(conn)
print(data)
if not data:
print("No data")
break
fb.write(data)
fb.flush()
print("Download complete\n")
SendRecieveProcedure.py
import struct
def send_msg(s, msg):
msg2 = struct.pack('>I', len(msg)) + msg
s.send(msg2)
def recv_msg(s):
# Read message length and unpack it into an integer
raw_msglen = s.recv(4)
print(raw_msglen)
if not raw_msglen:
return None
n = struct.unpack('>I',raw_msglen)[0]
# Read the message data
data = ' '
while len(data) < n:
packet = s.recv(n - len(data)).decode("cp437")
if not packet:
return None
data += packet
#print("hwllo",data )
return data
output prints correctly to the console, but if I go open up the file it's only writing starting lines.so what is the problem in code

Receive more than one message on more than one port Echo Server python

I am writing a echo server and client in Python, that implements a simple number guessing game. I know how to multiplex using select, that's fine. The other server I wrote achieves this. But now I am writing a new server (which is fairly similar), however it accepts connections from two ports rather than one, one port for player client, and one for admin which I will use eventually for the who command, returning all connected players.
My problem is, that after sending the initial greetings message, the clients receive feedback from the server on the first send, recv. But after that I cannot send any more messages to server (nothing gets sent from the clients), I have been searching and playing around for hours, to no avail. Any help would be appreciated. Thanks!
# MULTIPLEX SERVER
import socket, select, time, random, ssl, sys, os
# VARS
EXP = 1
HOST = '127.0.0.1'
PORT_P = 4000
PORT_A = 4001
BUFFSZ = 1024
BKLOG = 5
GREETS = 'Greetings'
INPUTS = []
OUTPUTS = []
CLIENT_ADDRS = {}
CLIENT_ANS = {}
CLIENTS = ""
_adm_rtnMSG = 'Admin_Greetings'
# Function to determine how far the player is
# from the chosen random number
def Within(value, target):
diff = abs(target - value)
if diff > 3:
return 'Not even close, youth!'
else:
return 'Ooh, not to far: ' + str(diff) + ' away, keep trying...'
# END_FUNCTION
print('Server up and running...\n')
try:
for p in PORT_P, PORT_A:
INPUTS.append(socket.socket(socket.AF_INET, socket.SOCK_STREAM))
INPUTS[-1].setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
INPUTS[-1].bind((HOST, p))
INPUTS[-1].listen(BKLOG)
except socket.error(value, message):
if INPUTS[-1]:
INPUTS[-1].close()
INPUTS = INPUTS[:-1]
print('Failure to open socket: ' + message)
sys.exit(1)
while True:
READ_IO, WRITE_IO, ERROR = select.select(INPUTS, OUTPUTS, INPUTS)
for r in READ_IO:
for p in INPUTS:
if r is p:
(acpt_sock, addr) = p.accept()
print('Connection established with ', acpt_sock.getsockname())
CLIENT_ADDRS[acpt_sock] = addr
CLIENT_ANS[acpt_sock] = random.randrange(1, 20)
else:
data = acpt_sock.recv(BUFFSZ).decode()
acpt_sock.setblocking(0)
if data:
if 'Hello' in data:
print(CLIENT_ADDRS[acpt_sock], ' random number is: ', CLIENT_ANS[acpt_sock])
acpt_sock.send(b'Greetings\nGuess a random number between 1 & 20')
# drop elif here for admin cmd
elif 'Hi' in data:
acpt_sock.send(_adm_rtnMSG.encode())
else:
if int(data) == CLIENT_ANS[acpt_sock]:
acpt_sock.send(b'That was correct, Well done!')
else:
acpt_sock.send(str(Within(int(data), CLIENT_ANS[acpt_sock])).encode())
else:
print('Closing Connection # ', addr)
INPUTS.remove(acpt_sock)
acpt_sock.close()
del CLIENT_ADDRS[acpt_sock]
# PLAYER CLIENT
import socket
import re
# INIT VARS
HOST = '127.0.0.1'
PORT = 4000
INITSTR = 'Hello'
BUFF = 1024
# Set up socket
sender = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sender.connect((HOST, PORT))
sender.send(bytes((INITSTR), "ascii"))
print("Kirby Prompt FTW!\nConnected to Server via", HOST, "::", PORT, '\n')
rtnMSG = sender.recv(BUFF).decode()
print(rtnMSG)
# Simple loop to keep client alive
# to send and receive data from the server
while 'correct' not in rtnMSG:
_guess = input("(>',')> ")
sender.send(bytes((_guess), "ascii"))
rtnMSG = sender.recv(BUFF).decode()
print(rtnMSG)
sender.close()
# ADMIN CLIENT
import socket
import re
import ssl
# INIT VARS
HOST = '127.0.0.1'
PORT = 4001
INITSTR = 'Hi'
BUFF = 1024
# Set up socket
adm_sender = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
adm_sender.connect((HOST, PORT))
adm_sender.send(bytes((INITSTR), "ascii"))
print("Connected to Server as Admin via", HOST, "::", PORT, '\n')
rtnMSG = adm_sender.recv(BUFF).decode()
print(rtnMSG)
while True:
cmd = input('$ ')
adm_sender.send(bytes((cmd), "ascii"))
rtnMSG = adm_sender.recv(BUFF).decode()
print(rtnMSG)
adm_sender.close()

Categories

Resources