Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I make an outgoing socket to a SPECIFIC network interface?

Tags:

I have a server with two different network interfaces, each with a different IP address. How can I create a socket so it'll go out a specific IP address?

I'd prefer a python example, but the question is language agnostic, so shoot away.

EDIT: Please don't give me "You can't" as an answer. I mean, it is a computer. I can do anything I like to it, for example - I can programatically disable the one interface I don't want on the fly. I'm looking for something prettier.

like image 737
Mikle Avatar asked Dec 02 '08 21:12

Mikle


People also ask

How do I assign an IP address to a network interface?

To assign a unique IP address to each network interface, issue the TCPIP [TCPIP] IDENTITY (TCPIP ID) command at the TCP/IP host for which you are assigning an IP address . You can issue IPv4 and IPv6 TCPIP ID commands on the same network interface.

What are the two main ways IP addresses are assigned to a network adapter?

This article describes how to change the Internet Protocol (IP) address that is assigned to a network adapter. An IP address may be assigned automatically if your network has a Dynamic Host Configuration Protocol (DHCP) server, or you can specify an IP address.


2 Answers

You can certainly bind a socket to a specific device.

I don't know how to do it in python, but using the berkeley socket api (in C) you need to call setsockopt(), using the option SO_BINDTODEVICE.

You pass in an interface descriptor, which is of type struct ifreq. Ideally you would get the contents of the interface descriptor by using ioctl(), and requesting SIOCGIFINDEX - passing the name of the interface (eg. eth0) as an argument.


edit: Just did a quick search and found this documentation of the socket methods in python. setsockopt() is amongst them.

like image 96
Andrew Edgecombe Avatar answered Oct 01 '22 18:10

Andrew Edgecombe


Just a little note - what I really needed is to bind to a specific IP, and just for the sake of completeness, the solution is to bind the socket after creation. Source in python:

import socket s = socket.socket() s.bind(("127.0.0.1", 0)) s.connect(("321.12.131.432", 80)) 
like image 28
Mikle Avatar answered Oct 01 '22 19:10

Mikle