Python Socket问题:端口被识别为字符串引发TypeError报错
Hey there! Let's break down what's going wrong with your script and how to fix it quickly.
The Root Cause
The error you're seeing happens because when you use input() to grab the port number, Python returns it as a string by default. But the connect_ex() method of a socket object expects the port to be an integer—that's why you're hitting this type mismatch error.
The Quick Fix
All you need to do is convert the port input to an integer using the int() function. Here's how to adjust that part of your script:
# Replace this line: port = input("Enter TCP/UDP port: ") # With this: port = int(input("Enter TCP/UDP port: "))
Making It More Robust (Optional)
If you want to handle cases where someone might enter a non-numeric value (like letters or symbols), you can add a simple error-checking loop with try-except blocks to make your script more user-friendly:
while True: try: port = int(input("Enter TCP/UDP port: ")) break # Exit loop if input is a valid integer except ValueError: print("Oops, that's not a valid number! Please enter a numeric port.") # Now use the port variable in your connect_ex call if s.connect_ex((ip, port)): # Your existing logic here pass
Verifying the Fix
After making this change, when you enter 443 as the port, Python will treat it as an integer instead of a string, and the connect_ex() method should run without throwing that TypeError.
内容的提问来源于stack exchange,提问作者agusbava

