tags:

views:

69

answers:

2

Hi, I need to get the file descriptor to use in ioctl() calls for an ethernet port in Linux. Not sure how to do this.

+2  A: 

Just use the file descriptor of an open socket, using the name of the device in the ifreq structure passed to ioctl(), assuming your program has adequate permissions to do so.

From the docs:

Linux supports some standard ioctls to configure network devices. They can be used on any socket's file descriptor regardless of the family or type. They pass an ifreq structure:

The socket need not be bound to the target device, or be of any specific family. Any open socket fd will do (again, with appropriate privileges), just open one for your specific task, wait for ioctl() to return and close it.

See man 7 netdevice for more, or here if you don't have the appropriate documentation packages installed (hint, the package is usually named manpages-dev or manpages-devel, depending on your distro)

You can also take a look at the source to the net-tools package, which may be named differently depending on your distro. That's the source to ifconfig (Debian / Ubuntu here).

Sorry for the original ambiguity, I thought you were trying to configure a special multi function device (not sure why now, perhaps lack of sleep).

Tim Post
Sorry, not sure where the file I am looking to open would be. Just thought using ioctl would be easier than parsing ifconfig.
Terminal
@Terminal - edited my answer for clarity.
Tim Post
@Terminal - And generally, yes, it is .. depending on what you are doing.
Tim Post
+1  A: 

You can do something like this fd = socket(PF_INET, SOCK_DGRAM, IPPROTO_IP)

Use strace to see what functions ifconfig calls.

Daniel Băluţă
That particular ioctl() doesn't care about the family, or even if the socket is bound to the interface in question.
Tim Post
You are right, but this call is used by ifconfig eth0 <ip>, to setup an ip address on eth0.
Daniel Băluţă
I think you meant "what functions **ifconfig** calls" ? Still, regardless, any open socket will work. The 'magic' is specified at the address of the initialized `ifreq` structure, passed to the kernel via `ioctl()`.
Tim Post
So does the fd even need to be valid? Could I just use 1 as the first parameter?
Terminal
@Terminal: Yes, the `fd` has to be a valid file descriptor for an open socket. This is so that the kernel knows to pass your `ioctl()` on to the socket `ioctl()` implementation, not any of the umpteen other `ioctl()` implementations for other types of files.
caf