Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to bind socket to an interface in python (socket.SO_BINDTODEVICE missing)

Tags:

python

sockets

This is probably a very simple thing. I'm new to python so don't crucify me.

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET, IN.SO_BINDTODEVICE, "eth1"+'\0')

the above command gives me:

NameError: name 'IN' is not defined

the only import I have is

import socket
like image 903
user916499 Avatar asked Aug 28 '11 14:08

user916499


3 Answers

If you don't understand the error message, it means you're referring a name IN which is not available at that point. Your code snippet is likely missing an import statement.

The socket module may not offer SO_BINDTODEVICE for portability reasons. If you are absolutely sure that you're running on Linux that supports it, try replacing it with it's numerical value, which is 25:

s.setsockopt(socket.SOL_SOCKET, 25, "eth1"+'\0')

Or for python 3:

s.setsockopt(socket.SOL_SOCKET, 25, str("eth1" + '\0').encode('utf-8'))
like image 127
hamstergene Avatar answered Nov 15 '22 14:11

hamstergene


In Python, SO_BINDTODEVICE is present in IN module. Importing IN will solve the problem.

import socket
import IN

sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.setsockopt(socket.SOL_SOCKET, IN.SO_BINDTODEVICE, "eth0")
like image 28
rashok Avatar answered Nov 15 '22 12:11

rashok


You may even "export" a missing option:

if not hasattr(socket,'SO_BINDTODEVICE') :
    socket.SO_BINDTODEVICE = 25

then

sock.setsockopt(socket.SOL_SOCKET, socket.SO_BINDTODEVICE, interface+'\0')
like image 42
jno Avatar answered Nov 15 '22 12:11

jno