tags:

views:

42

answers:

2

I am running my code on multiple VPSes (with more than one IP, which are set up as aliases to the network interfaces) and I am trying to figure out a way such that my code acquires the IP addresses from the network interfaces on the fly and bind to it. Any ideas on how to do it in python without adding a 3rd party library ?

Edit I know about socket.gethostbyaddr(socket.gethostname()) and about the 3rd party package netifaces, but I am looking for something more elegant from the standard library ... and parsing the output of the ifconfig command is not something elegant :)

A: 

The IP addresses are assigned to your VPSes, no possibility to change them on the fly.

You have to open a SSH tunnel to or install a proxy on your VPSes.

I think a SSH tunnel would be the best way how to do it, and then use it as SOCKS5 proxy from Python.

leoluk
Sorry, maybe I didn't phrase it right (English is not my mother tongue) ... I am trying to get the IP addresses of all network interfaces on that server. Is this more clear? Thanks.
hyperboreean
A: 

This is how to get all IP addresses of the server the script is running on:

(this is as much elegant as possible and it only needs the standard library)

import socket
import fcntl
import struct
import array

def all_interfaces():
    max_possible = 128  # arbitrary. raise if needed.
    bytes = max_possible * 32
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    names = array.array('B', '\0' * bytes)
    outbytes = struct.unpack('iL', fcntl.ioctl(
        s.fileno(),
        0x8912,  # SIOCGIFCONF
        struct.pack('iL', bytes, names.buffer_info()[0])
    ))[0]
    namestr = names.tostring()
    return [namestr[i:i+32].split('\0', 1)[0] for i in range(0, outbytes, 32)]
leoluk