Python Guess Game Server-Client - python

Well here is a python server - client guess game programm.Well here my problem is that all works but the loop doesnt.More specificly i can only put one guess from the user.I just want the user to input values and when he finds the right answer the program will close.Right now i can insert only one value for some reason .
Server:
import socket
import random
s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
s.bind(("192.168.1.3",9000))
s.listen(5)
(c,a) = s.accept()
print ("Received connection from", a)
Hello=c.recv(10000).decode()
print(Hello)
greetings="Greetings!"
c.send((greetings+"\r\n").encode())
game=c.recv(10000).decode()
print (game)
ready="Ready For The Guess Game!"
c.send((ready+"\r\n").encode())
random_number = random.randint(1, 20)
running = 1
while running:
guess=c.recv(10000).decode()
guess=int(guess)
print(guess)
if guess <= random_number - 3:
far_message="Far!"
c.send((far_message+"\r\n").encode())
if guess >= random_number + 3:
far_message="Far!"
c.send((far_message+"\r\n").encode())
if guess == random_number - 2 or guess == random_number + 2 or guess == random_number + 1 or guess == random_number - 1:
close_message="close!"
c.send((close_message+"\r\n").encode())
if (guess==random_number):
correct_message="Correct!"
c.send((correct_message+"\r\n").encode())
running=0
c.close()
And the Client:
import socket
s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
s.connect(('192.168.1.3',9000))
Hello="Hello"
s.send((Hello +"\r\n").encode())
greetings=s.recv(10000).decode()
print(greetings)
game="Guess Game Please"
s.send((game +"\r\n").encode())
game=s.recv(10000).decode()
print (game)
running=1
while running:
guess = input("Enter your guess: ")
s.send(guess.encode())
close_message = s.recv(10000).decode()
print (close_message)
far_message = s.recv(10000).decode()
print(far_message)
correct_message = s.recv(10000).decode()
print(correct_message)
running=0
s.close()

You need only one response listener on the client side
while running:
guess = input("Enter your guess: ")
s.send(guess.encode())
response = s.recv(10000).decode()
print(response)
if response.startswith("Correct"):
running = 0

Related

error with python socket module, client closing immediately on startup

the issue with my program is as follows:
i've been working on a socket server for some rp stuff dont mind that part, the more worrisome part is the fact that now my client just closes after trying to fix a massive vulnerability where if you press enter it will show "invalid input" then press enter again it will just log you into the server itself via a prompt shown after login. that part isnt relevant only the fact that the client closes immediately when i open it, any advice or issues i should look at? you should also note that def passwd(): was added in attempt to fix the issue, what i did was put the password prompt in a function, then call the function after connecting via ngrok tunnel, the code is below:
import socket
from os import name as os_name, system
from colorama import init, Fore as cc
import select
import time
dr = DR = r = R = cc.LIGHTRED_EX
g = G = cc.LIGHTGREEN_EX
b = B = cc.LIGHTBLUE_EX
m = M = cc.LIGHTMAGENTA_EX
c = C = cc.LIGHTCYAN_EX
y = Y = cc.LIGHTYELLOW_EX
w = W = cc.RESET
HEADER = 64
clear = lambda: system('cls') if os_name == 'nt' else system('clear')
clear()
PORT = input("Enter Port Number > ")
FORMAT = "utf-8"
DISCONNECT_MESSAGE = "!disconnect"
SERVER = input("Enter Tunnel Address > ")
PORT1 = int(PORT)
ADDR = (SERVER, PORT1)
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.connect(ADDR)
passwd()
def send(msg):
message = msg.encode(FORMAT)
msg_length = len(message)
send_length = str(msg_length).encode(FORMAT)
send_length += b' ' * (HEADER - len(send_length))
client.send(send_length)
client.send(message)
print(client.recv(2048).decode(FORMAT))
clear()
def ssrselec():
ssr = input("Input User ID > ")
if ssr:
clear()
send(ssr)
time.sleep(2)
if not ssr:
clear()
print("INVALID INPUT")
client.close()
def select():
selec = input("Types: Internal, External\n\nSelect Database Type > ")
if selec:
clear()
send(selec)
time.sleep(2)
ssrselec()
if not selec:
clear()
print("INVALID INPUT")
client.close()
print("To disconnect type !disconnect\n")
def passwd():
inp = input("Input Database Password > ")
if inp:
clear()
send(inp)
time.sleep(2)
select()
if not inp:
clear()
print("INVALID INPUT")
client.close()
inp2 = input(" > ")
if inp2:
clear()
send(inp2)
time.sleep(2)
select()
if not inp2:
clear()
print("INVALID INPUT")
client.close()
clear()
select()
clear()
my linter shows that passwd() is called before it is declared.
You should define passwd() before it is called.
You can do this by defining it earlier in the code or by hoisting all functions with this at the end:
if __name__==`__main__`:
# some code

Server/Client in Python Socket program stalls in middle of execution

I am working on an assignment that entails socket-programming using Python. What I am trying to do is create a server called "dispatcher" and 3 clients that all run the same "car.py" file that will represent race cars. Each of the race cars will randomly select a speed between 0-120 mph every five seconds and send that speed to the server(aka dispatcher). The server will take the speeds of the three cars and compute how much distance is left until that car reaches the finish line. Once one or more cars reaches the finish line, the server will compute who the winner is and announce that to all three cars. The server will keep track of who is in the lead and will announce that to all three cars every five seconds.
The problem is that in the middle the program stalls and it seems that the server and one of the clients is both waiting for each other. Here is my code for the server:
import socket
import sys
import threading
from queue import Queue
NUMBER_OF_THREADS = 2
JOB_NUMBER = [1, 2]
queue = Queue()
all_connections = []
all_address = []
# Create a Socket ( connect two computers)
def create_socket():
try:
global host
global port
global s
host = '127.0.0.1'
port = 9999
s = socket.socket()
except socket.error as msg:
print("Socket creation error: " + str(msg))
# Binding the socket and listening for connections
def bind_socket():
try:
global host
global port
global s
print("Binding the Port: " + str(port))
s.bind((host, port))
s.listen(5)
except socket.error as msg:
print("Socket Binding error" + str(msg) + "\n" + "Retrying...")
bind_socket()
# Handling connection from multiple clients and saving to a list
# Closing previous connections when server.py file is restarted
def accepting_connections():
for c in all_connections:
c.close()
del all_connections[:]
del all_address[:]
while True:
try:
conn, address = s.accept()
s.setblocking(1) # prevents timeout
all_connections.append(conn)
all_address.append(address)
print("Connection has been established :" + address[0])
except:
print("Error accepting connections")
def start_turtle():
while True:
cmd = input('turtle> ')
if cmd == 'go':
start_race()
elif cmd == 'stop':
break
else:
print("Command not recognized")
# Starting the Race
def start_race():
# Setting the distance to the finish line of the three cars
distance1, distance2, distance3 = 50, 50, 50
try:
while True:
# Collecting Speed rates at MPH of the 3 cars
speed1 = all_connections[0].recv(4096)
speed2 = all_connections[1].recv(4096)
speed3 = all_connections[2].recv(4096)
print("\nSpeed of Car 1: " + str(speed1.decode("utf-8")))
print("Speed of Car 2: " + str(speed2.decode("utf-8")))
print("Speed of Car 3: " + str(speed3.decode("utf-8")) + "\n")
# Calculating the distance travelled by each car driving at the same speed for five minutes.
dist_travelled1 = int(speed1.decode("utf-8")) / 60 * 5
dist_travelled2 = int(speed2.decode("utf-8")) / 60 * 5
dist_travelled3 = int(speed3.decode("utf-8")) / 60 * 5
# The amount of distance that is left to reach the finish line.
distance1 -= round(dist_travelled1, 1)
distance2 -= round(dist_travelled2, 1)
distance3 -= round(dist_travelled3, 1)
# Seeing who is in the lead.
lead = min(distance1, distance2, distance3)
lead_flag = True
# Checking to see if Car1 won or not
if distance1 <= 0:
message1 = "You crossed the finish line!"
print("Car 1 crossed the finish line!")
all_connections[0].sendall(message1.encode("utf-8"))
lead_flag = False
else:
message1 = "You have " + str(round(distance1, 1)) + " more miles left to go."
print("Car 1 has " + str(round(distance1, 1)) + " more miles left to go.")
all_connections[0].sendall(message1.encode("utf-8"))
# Checking to see if Car2 won or not
if distance2 <= 0:
message2 = "You crossed the finish line!"
print("Car 2 crossed the finish line!")
all_connections[1].sendall(message2.encode("utf-8"))
lead_flag = False
else:
message2 = "You have " + str(round(distance2, 1)) + " more miles left to go."
print("Car 2 has " + str(round(distance2, 1)) + " more miles left to go.")
all_connections[1].sendall(message2.encode("utf-8"))
# Checking to see if Car3 won or not
if distance3 <= 0:
message3 = "You crossed the finish line!"
print("Car 3 crossed the finish line!")
all_connections[2].sendall(message3.encode("utf-8"))
lead_flag = False
else:
message3 = "You have " + str(round(distance3, 1)) + " more miles left to go."
print("Car 3 has " + str(round(distance3, 1)) + " more miles left to go.")
all_connections[2].sendall(message3.encode("utf-8"))
# Breaking from while loop if we have a winner.
if message1 == "You crossed the finish line!" or message2 == "You crossed the finish line!" or \
message3 == "You crossed the finish line!":
break
# Keeping track of who is in the lead
if lead_flag:
lead_message = ''
if lead == distance1:
lead_message = "\nCar 1 is in the lead!"
elif lead == distance2:
lead_message = "\nCar 2 is in the lead!"
elif lead == distance3:
lead_message = "\nCar 3 is in the lead!"
print(lead_message)
all_connections[0].sendall(lead_message.encode("utf-8"))
all_connections[1].sendall(lead_message.encode("utf-8"))
all_connections[2].sendall(lead_message.encode("utf-8"))
sys.stdout.flush()
# If multiple cars crossed the finish line during the last round, calculate who crossed the finish line first.
time_to_cross_finish1 = distance1 / (dist_travelled1 / 5)
time_to_cross_finish2 = distance2 / (dist_travelled2 / 5)
time_to_cross_finish3 = distance3 / (dist_travelled3 / 5)
# Determine the winner
winner = min(time_to_cross_finish1, time_to_cross_finish2, time_to_cross_finish3)
# Creating and sending messages to both winners and losers.
loser_message = "You Lost!"
winner_message = "You Won!"
if winner == time_to_cross_finish1:
print("Car 1 Won!")
all_connections[0].sendall(winner_message.encode("utf-8"))
all_connections[1].sendall(loser_message.encode("utf-8"))
all_connections[2].sendall(loser_message.encode("utf-8"))
elif winner == time_to_cross_finish2:
print("Car 2 Won!")
all_connections[0].sendall(loser_message.encode("utf-8"))
all_connections[1].sendall(winner_message.encode("utf-8"))
all_connections[2].sendall(loser_message.encode("utf-8"))
elif winner == time_to_cross_finish3:
print("Car 3 Won!")
all_connections[0].sendall(loser_message.encode("utf-8"))
all_connections[1].sendall(loser_message.encode("utf-8"))
all_connections[2].sendall(winner_message.encode("utf-8"))
except:
print("Error: Shutting Down")
# Create worker threads
def create_workers():
for _ in range(NUMBER_OF_THREADS):
t = threading.Thread(target=work)
t.daemon = True
t.start()
# Do next job that is in the queue (handle connections, send commands)
def work():
while True:
x = queue.get()
if x == 1:
create_socket()
bind_socket()
accepting_connections()
if x == 2:
start_turtle()
queue.task_done()
def create_jobs():
for x in JOB_NUMBER:
queue.put(x)
queue.join()
create_workers()
create_jobs()
And for the cars (All three clients run the same file):
import random
import time
import socket
import sys
# create an INET(IPv4), STREAMing(TCP) socket
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
except socket.error:
print('Failed to create socket')
sys.exit()
print('Socket Created')
host = '127.0.0.1'
port = 9999
s.connect((host, port))
print('Socket Connected to IP' + host)
# Function for calculating current speed
def speed():
# Using random number to determine speed group
marker = random.randrange(1, 100)
speed_ratio = ''
# Speed groups are chosen before actual speed in order to balance speed selection and make the program more
# realistic.
if marker == 1:
speed_ratio = 'Crash'
elif marker < 5:
speed_ratio = 'Too_Slow'
elif marker < 15:
speed_ratio = 'Slow'
elif marker < 65:
speed_ratio = 'Steady'
elif marker < 90:
speed_ratio = 'Fast'
elif marker < 100:
speed_ratio = 'Ultra_Fast'
elif marker == 100:
speed_ratio = 'Max_Speed'
# Based on ratio, exact speed is determined in mph
speed_range = {'Crash': 0,
'Too_Slow': random.randrange(1, 29),
'Slow': random.randrange(30, 59),
'Steady': random.randrange(60, 79),
'Fast': random.randrange(80, 109),
'Ultra_Fast': random.randrange(110, 119),
'Max_Speed': 120}
# Current speed is printed and sent to the server
current_speed = speed_range[speed_ratio]
print("\nCurrent Speed: " + str(current_speed))
s.sendall(str(current_speed).encode("utf-8"))
# Waits to receive calculation of how close it is to the finish line.
reply = s.recv(4096)
message = reply.decode("utf-8")
print(message)
# Waits to receive news of who is in the lead or who the winner is.
reply = s.recv(4096)
message = reply.decode("utf-8")
print(message)
# Exit upon winning or losing
if message == "You Won!" or message == "You Lost!":
return False
return True
# Main program: Calculates speed every five seconds. Each second represents what would be a minute in real time.
flag = True
now = time.time()
future = now + 5
while flag:
if time.time() > future:
flag = speed()
now = time.time()
future = now + 5
Here is what the console reads from the server program:
turtle: Binding the Port: 9999 Connection has been established
:127.0.0.1 Connection has been established :127.0.0.1 Connection has
been established :127.0.0.1 go
Speed of Car 1: 20 Speed of Car 2: 85 Speed of Car 3: 4
Car 1 has 48.3 more miles left to go. Car 2 has 42.9 more miles left
to go. Car 3 has 49.7 more miles left to go.
Car 2 is in the lead!
Here are the three client terminals:
Car 1:
Socket Created Socket Connected to IP127.0.0.1
Current Speed: 20 You have 48.3 more miles left to go.
Car 2 is in the lead!
Current Speed: 113
Car 2:
Socket Created Socket Connected to IP127.0.0.1
Current Speed: 85 You have 42.9 more miles left to go.
Car 2 is in the lead!
Current Speed: 78
Car 3:
Socket Created Socket Connected to IP127.0.0.1
Current Speed: 4 You have 49.7 more miles left to go. Car 2 is in the
lead!
As you can see from the output, Car 1 and Car 2 have produced another speed that was sent to the server while Car 3 has not. It seems that the server is sitting and waiting for Car 3 and Car 3 is waiting for the server and I don't know why. Car 3 implements the same exact code as the other cars. When I rerun the program it usually gets stuck at Car 3 but will sometimes get stuck at Car 2 and even Car 1 in the same way.
I am baffled at what the problem could be. It actually worked one single time after repeatedly rerunning the program but after rerunning right away after that with no changes whatsoever, it went back to this same problem. Any help would be greatly appreciated.

Client disconnects when another client connects to the server

I'm writing an Encrypted R-P-S (Rock, Paper, Scissors) Game with Python, and it works like this. The server is leading the game, and the two clients is just sending their choice to the server.
First, the server is waiting for 2 players to join, when 2 players have joined, he is starting the game and letting both of the clients to choice an option.
My problem is that when the first client connects, and then the another, the first client automatically disconnects.
So, I don't know how to handle both of the clients, and let the first client choose an option and then let the second choose option.
*Note: I'm using the same client file for both of the clients.
Server:
import socket
from Crypto.PublicKey import RSA
from Crypto.Cipher import PKCS1_OAEP
from time import sleep
def rules(first_choice, second_choice, mem1, mem2) -> str:
if (first_choice == 'R' and second_choice == 'P'
or first_choice == 'P' and second_choice == 'S'
or first_choice == 'S' and second_choice == 'R'):
return f'Result: Player 2 Won\nPlayer 1 Choice - {first_choice}\nPlayer 2 Choice - {second_choice}'
else:
return f'Result: Player 1 Won!\nPlayer 1 Choice - {first_choice}\nPlayer 2 Choice - {second_choice}'
class Connect:
def __init__(self):
players = 0
self.prikey = RSA.generate(1024)
self.pubkey = self.prikey.publickey()
self.token = PKCS1_OAEP.new(self.prikey)
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
sock.bind(('0.0.0.0', 21523))
sock.listen(2)
print('Waiting for at least 2 players, please wait.')
while True:
self.conn, self.addr = sock.accept()
players += 1
if players == 1:
print(f'Player 1 is {self.addr}')
self.player1 = self.addr
elif players == 2:
print(f'Player 2 is {self.addr}')
self.player2 = self.addr
self.connection()
def connection(self) -> None:
print('2 Players have joined, starting game in 5 seconds.\n')
sleep(5)
self.conn.send('Y'.encode())
self.game_play()
def game_play(self) -> None:
self.conn.send(self.pubkey.exportKey())
choice_1_cipher = self.conn.recv(1024)
choice_1_plain = self.token.decrypt(choice_1_cipher)
print('Got first choice, waiting for another choice..')
choice_2_cipher = self.conn.recv(1024)
choice_2_plain = self.token.decrypt(choice_2_cipher)
print('Got second answer, calculating winner!')
print(rules(choice_1_plain, choice_2_plain, self.player1, self.player2))
if __name__ == '__main__':
Connect()
Client:
import socket
import random
from Crypto.Cipher import PKCS1_OAEP
from Crypto.PublicKey import RSA
class Client:
def __init__(self):
self.prikey = RSA.generate(2048)
self.pubkey = self.prikey.publickey()
self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.sock.connect(('10.0.0.42', 21523))
data = self.sock.recv(1024).decode()
if data == 'Y':
self.start_game()
def start_game(self) -> None:
print('\n [R]ock | [P]aper | [S]cissors - ')
while True:
my_choice = input().upper()
if my_choice not in ['R', 'P', 'S']:
print('Invalid Input, input must be one of those R\\P\\S')
else:
user_pubkey = RSA.importKey(self.sock.recv(2048))
token = PKCS1_OAEP.new(user_pubkey)
cipher_choice = token.encrypt(my_choice.encode())
self.sock.send(cipher_choice)
if __name__ == '__main__':
try:
Client()
except Exception as e:
print(f'err: {e}')
except KeyboardInterrupt:
print('A player has pressed [Ctrl + C] to quit the game, game ended!')
self.conn in self.conn, self.addr = sock.accept() when the 2 client connects gets overwritten and the self.conn of the player1 is lost.
I guess you should assign the self.conn to self.player1_conn before returning to the beginning of the while loop waiting for the 2 player.
This is actually a recurrent problem in your script because when you say self.conn.send('Y'.encode()) self.conn is referring only to the second player connection (which i guess it's not what you intend to do).
You should separate the conn in player1_conn and player2_conn and then you'll be able to chose to which player send what you need.

How do I implement a timer on each question asked in a quiz?

I was attempting to create a quiz and one of the criteria is to limit the time available to solve for each question in the quiz. I looked up certain tutorials but some require an input of x seconds for the timer to go off while others looked more like a stopwatch...
I was wondering how do I do like a background timer that ticks down as soon as the question is printed out and skips to the next question if, for example the 30-second period has ended? I'm clueless in the timer function and was having problems to even try to implement them onto my codes. Could someone give out a few pointers so I can sorta progress further in implementing a working timer?
Thank you!
EDITED section below:
The timer that I want to implement onto my coding:
import time
import threading
def atimer():
print("Time's up.")
a_timer = threading.Timer(10.0, atimer)
a_timer.start()
print("")
This is the whole coding that I tried to implement the timer into.
I noticed that when I tried to define qtimer to just print 1 or 2 lines of statements the timer works but I want the timer to stop and go to second question or stop and give the user another attempt to retry the question, so I tried to attach a bunch of codes after the definition and it didn't work. I know I'm most probably doing something wrong here since I'm not quite familiar with time or threading functions. Is there a workaround?
def qtimer():
print("I'm sorry but your time is up for this question.")
print("You may have another attempt if you wish to, with reduced marks allocated.")
response1 = input("Type 'Yes' for another attempt, anything else to skip: ")
if response1 == "Yes":
Answ = input("Which option would you go for this time?: ")
Answ = int(Answ)
if possible[Answ - 1] == qaItem.corrAnsw:
print("Your answer was correct.")
corr += 1
marks += 0.5 * qaItem.diff
else:
print("Your answer was wrong.")
print("Correct answer was: " + qaItem.corrAnsw)
print("Explanation: " + qaItem.expl)
print("")
else:
print("Correct answer was: " + qaItem.corrAnsw)
print("Explanation: " + qaItem.expl)
print("")
class A:
def __init__(self, question, correctAnswer, otherAnswers, difficulty, explanation):
self.question = question
self.corrAnsw = correctAnswer
self.otherAnsw = otherAnswers
self.diff = difficulty
self.expl = explanation
qaList = [A("What is COVID-19?", "Coronavirus Disease 2019", ["Wuhan virus", "I don't understand...", "Coronavirus Disease v19"], 1, "Explanation 1"),
A("What describes COVID-19?", "A disease", ["A virus", "A parasite", "A bacteriophage"], 1, "Explanation 2"),
A("What causes COVID-19?", "SARS-CoV-2", ["Coronavirus", "Mimivirus", "Rubeola Virus"], 1, "Explanation 3"),
A("Which of the following is used in COVID-19 treatment?", "Lopinavir / Ritonavir ", ["Midazolam / Triazolam", "Amiodarone", "Phenytoin"], 2, "Explanation 4"),
A("Which of the following receptors is used by COVID-19 to infect human cells?", "ACE-2 Receptors", ["ApoE4 Receptors", "TCR Receptors", "CD28 Receptors"], 3, "Explanation 5")]
corr = 0
marks = 0
random.shuffle(qaList)
for qaItem in qaList:
q_timer = threading.Timer(5.0, qtimer)
q_timer.start()
print(qaItem.question)
print("Possible answers are:")
possible = qaItem.otherAnsw + [qaItem.corrAnsw]
random.shuffle(possible)
count = 0
while count < len(possible):
print(str(count+1) + ": " + possible[count])
count += 1
print("Please enter the number of your answer:")
Answ = input()
Answ = str(Answ)
while not Answ.isdigit():
print("That was not a number. Please enter the number of your answer:")
Answ = input()
Answ = int(Answ)
Answ = int(Answ)
while Answ > 4 or Answ < 1:
print("That number doesn't correspond to any answer. Please enter the number of your answer:")
Answ = input()
Answ = int(Answ)
if possible[Answ-1] == qaItem.corrAnsw:
print("Your answer was correct.")
corr += 1
marks += 1 * qaItem.diff
else:
print("Your answer was wrong.")
response = input("Would you want to try again? If so, input 'Yes' to attempt it again, if not just input whatever!")
if response == "Yes":
Answ = input("Which option would you go for this time?: ")
Answ = int(Answ)
if possible[Answ - 1] == qaItem.corrAnsw:
print("Your answer was correct.")
corr += 1
marks += 0.5 * qaItem.diff
else:
print("Your answer was wrong.")
print("Correct answer was: " + qaItem.corrAnsw)
print("Explanation: " + qaItem.expl)
print("")
else:
print("Correct answer was: " + qaItem.corrAnsw)
print("Explanation: " + qaItem.expl)
print("")
print("You answered " + str(corr) + " of " + str(len(qaList)) + " questions correctly.")
print("You have achieved a total score of " + str(marks) + ".")
Even with a timer, the main thread can't proceed past waiting for the user to input a number; so if the user doesn't nothing, the timer function runs, and once it has finished the main thread is still waiting for input at
print("Please enter the number of your answer:")
Answ = input()
You could have a global flag that the timer thread sets to tell the main thread to treat the input received as response1 in the timer code, and also have a flag to tell the timer that an answer was received, and so on, and it quickly becomes rather complicated.
So rather than trying to work around the blocking call to input by communicating between the timer and main thread, take the non-blocking input example from https://stackoverflow.com/a/22085679/1527 and stop the loop early if the time is up.
def timed_input(msg, timeout=10):
kb = KBHit()
print(msg)
end_time = time.time() + timeout
warn_time = 5
result = None
while True:
if kb.kbhit():
c = kb.getch()
if '0' <= c <= '9':
result = int(c)
break
print(c)
if time.time() > end_time:
print('time is up')
break
if time.time() > end_time - warn_time:
print(f'{warn_time}s left')
warn_time = warn_time - 1
kb.set_normal_term()
return result
# Test
if __name__ == "__main__":
result = timed_input('Enter a number between 1 and 4')
if result is None:
print('be quicker next time')
elif 1 <= result <= 4:
print('ok')
else:
print(f'{result} is not between 1 and 4')
Note also that breaking up into smaller functions helps make the code easier to follow, the logic of the test doesn't need to know about the logic of the timeout.

TypeError: 'str' object not callable [Python] [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
I've been trying to run this little port scanner-ish program for a while and I still don't know why it's giving me this error: [EDIT: I renamed the IP string into IPadd since it might have been confusing the two edited and now it says this error]
File "thing.py", line 63, in portScan
if (str(type(fin_scan_resp))=="<type 'NoneType'>"):
TypeError: 'int' object is not callable
this is the code:
#!/usr/bin/python
import logging
logging.getLogger("scapy.runtime").setLevel(logging.ERROR)
from scapy.all import *
from socket import *
import urllib2
import sys
def portScan(target):
validate = 0
print("Simple Port Scanner v1.0")
print("Available port scans")
print("[1] TCP Connect")
print("[2] SYN")
print("[3] ACK")
print("[4] FIN")
#print("[5] XMAS")
print("\n COMMON PORTS: 20, 21, 23, 80")
getport = raw_input("What port will you scan?: ")
port = int(getport)
while validate != 1:
type = input("What kind of scan do you want to do?: ")
print "Selected", type
validate = 1
try:
IPadd = gethostbyname(target)
print(IP) #trace
except:
print("ERROR: Cannot resolve connection... Exiting program")
if type == 1:
tcpconn = socket(AF_INET, SOCK_STREAM)
tcpconn.settimeout(0.255)
#for port in range(20, 25):
isopen = tcpconn.connect_ex((IPadd, port))
if isopen == 0:
print ("TCP Connect: Port " + getport + " is Open")
else:
print ("TCP Connect: Port " + getport + " is Closed")
tcpconn.close()
elif type == 2:
print ("SYN")
synconn = socket(AF_INET, SOCK_STREAM)
synconn.settimeout(0.255)
elif type == 3:
print ("ACK")
elif type == 4:
dst_ip = IPadd
src_port = RandShort()
dst_port= port
fin_scan_resp = sr1(IP(dst=dst_ip)/TCP(dport=dst_port,flags="F"),timeout=10)
if (str(type(fin_scan_resp))=="<type 'NoneType'>"):
print "Open|Filtered"
elif(fin_scan_resp.haslayer(TCP)):
if(fin_scan_resp.getlayer(TCP).flags == 0x14):
print "Closed"
elif(fin_scan_resp.haslayer(ICMP)):
if(int(fin_scan_resp.getlayer(ICMP).type)==3 and int(fin_scan_resp.getlayer(ICMP).code) in [1,2,3,9,10,13]):
print "Filtered"
print ("FIN")
else:
print("Invalid input")
validate = 0
def getTarget():
target = raw_input("Enter target Host name/IP Address: ")
'''
#Validation of ip address still not working
#chk = socket(AF_INET, SOCK_STREAM)
try:
socket.inet_aton(target)
except socket.error:
print("IP address is invalid. QUITTING")
chk.close()
'''
return target
def main():
validate = 0
print("Launch which scan?")
print("[1] Simple Port Scanner v1.0")
print("[2] Service Fingerprinting v1.0")
print("[3] OS Fingerprinting v1.0")
print("[x] Exit")
while validate != 1:
firstMenu = raw_input("Choice: ")
if firstMenu == "1":
print("\n")
validate = 1
name = getTarget()
portScan(name)
elif firstMenu == "2":
print("yep")
validate = 1
elif firstMenu == "3":
print("this")
validate = 1
elif firstMenu == "x":
print("Closing...")
validate = 1
else:
print("Invalid choice")
main()
That part where there is supposed to be some error runs fine when I run that part on another .py file so I don't understand what's causing this and it's just frustrating
You are assigning a string to IP:
try:
IP = gethostbyname(target)
print(IP) #trace
but you are also trying to use the scapy IP() object:
fin_scan_resp = sr1(IP(dst=dst_ip)/TCP(dport=dst_port,flags="F"),timeout=10)
The string masks the object. Rename the string to ip (lowercase), everywhere in the portScan() function:
try:
ip = gethostbyname(target)
print(ip) #trace
# ...
#for port in range(20, 25):
isopen = tcpconn.connect_ex((ip, port))
# ...
elif type == 4:
dst_ip = ip
Instead of the rather ridiculous line:
if (str(type(fin_scan_resp))=="<type 'NoneType'>"):
use:
if fin_scan_resp is None:
although you really should not use type as a local variable as it masks the built-in function.

Categories

Resources