0

I am trying to bind a socket to a interface in my application in Linux.I found some code stuff here but when I tried using this I was getting -1 as return value from setsockopt

Here is my sample code:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/ioctl.h>
#include <net/if.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include "newfile.h"


int main (int argc, const char* argv[])
{

scktfd = socket(AF_INET, SOCK_DGRAM, 0); 
char *opt;
opt = "eth0";

struct ifreq Interface; 
memset(&Interface, 0, sizeof(Interface));
strncpy(Interface.ifr_ifrn.ifrn_name, "eth0", IFNAMSIZ); 

int rtrn;
rtrn = setsockopt(scktfd, SOL_SOCKET, SO_BINDTODEVICE,&Interface, sizeof(Interface));

  return 0;
}

I tried by modifying the code by looking at other examples but it didn't work. What might be the problem.

Community
  • 1
  • 1
Paul Sen
  • 526
  • 1
  • 4
  • 20

1 Answers1

2

After discussion in chat the problem was that the code was not run as root, as stated first by TripeHound.

Binding to network interfaces is not allowed to anyone (you can spy programs/users network data…), so using root or a user with correct access to device is needed.

hexasoft
  • 677
  • 3
  • 9