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

如何通过Python脚本让DigitalOcean出站流量走浮动IP?

How to Route Python Outbound Traffic Through Your DigitalOcean Floating IP

Hey there, I’ve wrestled with this exact issue on DigitalOcean Droplets before—let me walk you through how to get your Python script’s outbound traffic routing through that floating IP you’ve set up. You already found the anchor IP via ip addr show eth0, which is a great start—let’s put that to use.

Quick Background

DigitalOcean links floating IPs to your Droplet using that anchor IP as an internal mapping. When you send traffic from the anchor IP, it gets NAT’d to your public floating IP on the way out. Alternatively, you can often bind directly to the floating IP itself since it’s assigned to your Droplet’s network stack.


1. Using requests (For HTTP/HTTPS Requests)

If you’re using requests (the go-to for most web requests), you’ll need a custom adapter to force the connection to use your floating/anchor IP as the source. Here’s how to set it up:

First, import the necessary bits:

import requests
from requests.adapters import HTTPAdapter
from urllib3.poolmanager import PoolManager
import socket

Next, create a custom adapter that binds to your chosen source IP:

class SourceAddressAdapter(HTTPAdapter):
    def __init__(self, source_address, **kwargs):
        self.source_address = source_address
        super().__init__(**kwargs)

    def init_poolmanager(self, connections, maxsize, block=False):
        self.poolmanager = PoolManager(
            num_pools=connections,
            maxsize=maxsize,
            block=block,
            source_address=self.source_address
        )

Now hook this adapter into a requests session. Replace YOUR_FLOATING_IP with your actual public floating IP (or swap it for the anchor IP if you hit snags):

# Use your floating IP (e.g., "45.55.123.45") or anchor IP (e.g., "10.128.0.100")
SOURCE_IP = "YOUR_FLOATING_IP"
# Use 0 to let the OS pick a random port, or specify one if needed
SOURCE_PORT = 0

session = requests.Session()
# Mount the adapter for both HTTP and HTTPS
session.mount("http://", SourceAddressAdapter((SOURCE_IP, SOURCE_PORT)))
session.mount("https://", SourceAddressAdapter((SOURCE_IP, SOURCE_PORT)))

# Test it out—this will show the IP the remote server sees
response = session.get("https://api.ipify.org")
print(f"Remote server sees my IP as: {response.text}")

Pro tip: If the floating IP doesn’t work right away, try using the anchor IP instead. I’ve had cases where that was the magic fix.


2. Using Native socket (Lower-Level Control)

If you’re working directly with sockets (for non-HTTP traffic or more control), you can bind the socket to your source IP before connecting to the destination:

import socket

# Replace with your floating/anchor IP
SOURCE_IP = "YOUR_FLOATING_IP"
# Example destination: check our outbound IP
DEST_HOST = "api.ipify.org"
DEST_PORT = 443

# Create a TCP socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# Bind to our source IP (0 means random port)
sock.bind((SOURCE_IP, 0))
# Connect to the destination
sock.connect((DEST_HOST, DEST_PORT))

# Send a simple HTTPS request (simplified for demo)
request = b"GET / HTTP/1.1\r\nHost: api.ipify.org\r\nConnection: close\r\n\r\n"
sock.sendall(request)

# Read and print the response
response = b""
while True:
    data = sock.recv(1024)
    if not data:
        break
    response += data

print(response.decode())
sock.close()

3. Make Sure It’s Working

After running either script, check the output from api.ipify.org—it should show your floating IP, not your Droplet’s regular public IP. If it’s still showing the regular IP:

  • Double-check that your floating IP is properly assigned to the Droplet in the DigitalOcean dashboard
  • Try swapping between the floating IP and anchor IP in your script
  • Verify there are no custom iptables rules overriding your source IP selection

Troubleshooting Quick Hits

  • If you get a PermissionError, you’re probably trying to use a privileged port (1-1023)—either pick a higher port or run the script as root.
  • If connections time out, check your Droplet’s firewall rules to ensure outbound traffic from the floating IP is allowed (DigitalOcean’s default firewall usually permits this, but custom rules might block it).
  • For other libraries like httpx or urllib3, look for options to set the source_address—most modern HTTP libraries support this.

内容的提问来源于stack exchange,提问作者Luca Squadrone

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 04:23:35