Akhil Sundar
Akhil Sundar

Reputation: 1317

IP switching using Python inside AWS Ubuntu EC2 instance

Actually I have some secondary private IPs , attached to my ec2 instance, each associated with a public Elastic IP. And I have a piece of python code to perform some API requests using python-requests. I need to set a custom source IP before sending out each requests, from the already attached IPs list.

Tried below code but ended in error:

import socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.bind(('X.X.X.X', 20))

Thanks in advance

Upvotes: 1

Views: 172

Answers (1)

Anon Coward
Anon Coward

Reputation: 10825

The elastic IP address exists behind a 1:1 NAT, so you need to bind the local IP address that the instance is behind. You can ask the metadata store to get the public/local IP addresses for each network adapter.

Most of the time doing so is pretty straightforward:

import requests
import socket

metadata = "http://169.254.169.254/latest/meta-data/network/interfaces/macs/"

for mac_id in requests.get(metadata).text.split("\n"):
    local_ip = requests.get(metadata + mac_id + "local-ipv4s").text
    public_ip = requests.get(metadata + mac_id + "public-ipv4s").text
    print("{} has local IP of {} and public IP of {}".format(mac_id, local_ip, public_ip))

    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock.bind((local_ip, 1234))

Upvotes: 2

Related Questions