Virtual Box与亚马逊实例通信报错:Python socket.error: Connection refused
Let’s work through the common issues that could be causing this connection failure—since you’ve already covered the basics (port opening, DMZ setup, bridge mode, firewall disabled), we’ll dig into the less obvious checks:
Confirm your VM’s listener is bound to the correct address
It’s incredibly common for socket programs to default to listening only on127.0.0.1(localhost), which means they’ll only accept connections from inside the VM, not external sources like your AWS instance.
Run this command on your Ubuntu VM to verify:ss -tulpn | grep 2019Look for a line with
LISTENin it. The address column should show0.0.0.0:2019(accepts connections from any IP) or your VM’s LAN IP (e.g.,192.168.1.100:2019). If it shows127.0.0.1:2019, modify your Python code to bind to0.0.0.0instead oflocalhost.Double-check your VM’s LAN IP matches your DMZ configuration
Bridge mode can assign a new IP if your router’s DHCP lease expires. Confirm your VM’s current IP with:ip aCompare this to the IP you set in your router’s DMZ settings. If they don’t match, update the DMZ to use the correct active IP.
Test connectivity from your AWS instance to your public IP
First, get your home network’s public IP (you can find this in your router’s admin panel or by running a public IP lookup from a device on your LAN). Then from your AWS DL AMI instance, run:telnet <your-public-ip> 2019If this fails, either your ISP is blocking incoming traffic on port 2019, or your DMZ/port forwarding isn’t properly configured. If telnet works but your Python code doesn’t, you likely have a protocol mismatch (TCP vs UDP) in your code.
Verify VirtualBox’s bridge mode uses the right physical adapter
If your host machine has multiple adapters (e.g., Wi-Fi and Ethernet), VirtualBox might be bridging to the wrong one. Open VirtualBox, go to your VM’s Settings > Network > Adapter 1, ensure "Bridge Adapter" is selected, and the dropdown matches the adapter connected to your LAN (the one your router uses for wired/wireless traffic).Check for residual iptables rules (even with ufw disabled)
Ubuntu can sometimes leave leftover iptables rules after turning off ufw. List all rules with:sudo iptables -L -nLook for any
REJECTorDROPrules targeting port 2019. If you find them, flush the rules with:sudo iptables -FRule out protocol mismatch (TCP vs UDP)
You mentioned opening both protocols on port 2019, but make sure your AWS client uses the same protocol as your VM’s server:- If your VM runs a TCP listener, your AWS client must use
socket.SOCK_STREAM, notSOCK_DGRAM. - UDP doesn’t use a "connection" step, so a "connection refused" error here almost always means you’re mixing TCP and UDP in your client/server code.
- If your VM runs a TCP listener, your AWS client must use
内容的提问来源于stack exchange,提问作者Alberto Fernández

