You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python Socket问题:端口被识别为字符串引发TypeError报错

Fixing the "TypeError: an integer is required (got type str)" in Your Python Socket Script

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 09:35:47