05-20-07 12:17 AM
On May 5, 2:46 pm, Peyman <peyman.ta...@gmail.com> wrote:
> I'm implementing a program which routes packets in a ring network.
> what it does is that it will be running on every machine in the
> network which don't actually use IP for addressing, but only integers,
> so that every machine has a unique integer as its address, and two
> NICs, which one is connected to the left machine, one two right, no
> hub or switch, all cross cables. now, this program, reads every packet
> from eth0 and if it doesn't belong to that particular machine, then
> writes the packet to eth1. how can i make sure that read(), reads from
> eth0 and write(), writes to eth1 (only)? btw, i'm using raw sockets (i
> don't think there's any alternative for that. is there?).
> I appreciate any help, or pointer to help.
I found the answer and so I'm just answering my self in case someone
else was looking for the solution can find it here:
First of all, as I'm not using IP so I need to use PF_PACKET (packet
sockets) and which deals with link layer packets.
After that, I need to find the interface index of each interface (0 is
only for reading, and binds to every interface) using ioctl() with
SIOGIFINDEX and a struct ifreq parameter, and then declare a variable
of struct sockaddr_ll and set its member variable sll_ifindex to the
ifreq.ifr_ifindex, and finally bind the socket descriptor to the
specific sockaddr_ll. Here is the code:
if (-1 == (in_sd = socket(PF_PACKET, SOCK_RAW,
htons(ETH_P_ALL)))) {
perror("socket");
exit(EXIT_FAILURE);
}
if (-1 == (out_sd = socket(PF_PACKET, SOCK_RAW,
htons(ETH_P_ALL)))) {
perror("socket");
exit(EXIT_FAILURE);
}
struct ifreq in_rq, out_rq;
strcpy(in_rq.ifr_name, "eth0");
strcpy(out_rq.ifr_name, "eth1");
// find the interface index of the interface
ioctl(in_sd, SIOGIFINDEX, &in_rq);
ioctl(out_sd, SIOGIFINDEX, &out_rq);
struct sockaddr_ll in_addr, out_addr;
memset(&in_addr, '\0', sizeof in_addr);
memset(&out_addr, '\0', sizeof out_addr);
in_addr.sll_family = AF_PACKET;
out_addr.sll_family = AF_PACKET;
// accept every packet with whatever protocol, do not filter
in_addr.sll_protocol = htons(ETH_P_ALL);
out_addr.sll_protocol = htons(ETH_P_ALL);
in_addr.sll_ifindex = in_rq.ifr_ifindex;
out_addr.sll_ifindex = out_rq.ifr_ifindex;
if (-1 == bind(in_sd, (const struct sockaddr *)&in_addr,
sizeof in_addr)) {
perror("bind");
exit(EXIT_FAILURE);
}
if (-1 == bind(out_sd, (const struct sockaddr *)&out_addr,
sizeof out_addr)) {
perror("bind");
exit(EXIT_FAILURE);
}
[ Post a follow-up to this message ]
|