How to get the interface I am connected to

118 Views Asked by At

I am trying to implement an application which receives a packet(ICMP maybe) on a tap interface. I have the code something like this.

strcpy(ifName, "tap0");
if ((sockfd = socket(PF_PACKET, SOCK_RAW,0) == -1) {
    perror("ERROR: socket");    
}
retVal = setsockopt(sockfd, SOL_SOCKET,  SO_REUSEADDR,
                        (char *)&sockopt, sizeof(sockopt)); // int sockopt

setsockopt(sockfd, SOL_SOCKET,SO_BINDTODEVICE, ifName, IFNAMSIZ-1);
max_sd = sockfd;
FD_SET(sockfd, &readfds);
// Similarly I have other fd's for tap1 and tap2 set to this &readfds

timeout.tv_sec  = 30;
timeout.tv_usec = 0;

retVal = select(max_sd + 1, &readfds, NULL,NULL,&timeout);

if(retVal == 1){
    // Now I know I got some message on one of the tap interface. How do I find out which
one ??
}

TWO QUESTIONS :

  1. Now once I receive something on select, how do I find out on which tap interface did the packet arrive ?

  2. Also how can I test this code. I have these interface UP , how do I inject packets so that this receive function will work ? Can someone give the command ? ping should work(it sends ICMP packet). What is the correct command. I tried "ping -I tap0 localhost"

3

There are 3 best solutions below

0
Rags On BEST ANSWER

You can have a list of fd"s saved. Just a sample code

 // say you have 5 fd save in FD[] // have a mapping from fd's to tap interfaces
 // fd[1] -- tap1
 //fd[2] -- tap2 something like this
for(int i=0;i<5;i++){
   if(FD_ISSET(fd[i],&readfd)){
     //you have the fd, look up corresponding interface
  }
}
0
harper On

You can't find out at which adapter (or interface) a packet arrive with one socket.

Set up one socket per interface and receive with both sockets.

2
Ankit Kumar On

you need to open multiple sockets, one for each interface. the packet received on one interface will not be seen on any other interface. :)

There are separate RecvQ/TransQ for each Interface.