00001
00002
00003
00004
00005
00006
00007
00008
00009 #include "config.h"
00010
00011 #include <sys/types.h>
00012 #include <sys/ioctl.h>
00013 #include <sys/socket.h>
00014
00015 #include <net/if.h>
00016 #include <features.h>
00017 #if __GLIBC__ >= 2 && __GLIBC_MINOR >= 1
00018 #include <netpacket/packet.h>
00019 #include <net/ethernet.h>
00020 #else
00021 #include <asm/types.h>
00022 #include <linux/if_packet.h>
00023 #include <linux/if_ether.h>
00024 #endif
00025 #include <netinet/in.h>
00026
00027 #include <assert.h>
00028 #include <errno.h>
00029 #include <stdio.h>
00030 #include <stdlib.h>
00031 #include <string.h>
00032 #include <unistd.h>
00033
00034 #include "dnet.h"
00035
00036 struct eth_handle {
00037 int fd;
00038 struct ifreq ifr;
00039 struct sockaddr_ll sll;
00040 };
00041
00042 eth_t *
00043 eth_open(const char *device)
00044 {
00045 eth_t *e;
00046 int n;
00047
00048 if ((e = calloc(1, sizeof(*e))) != NULL) {
00049 if ((e->fd = socket(PF_PACKET, SOCK_RAW,
00050 htons(ETH_P_ALL))) < 0)
00051 return (eth_close(e));
00052 #ifdef SO_BROADCAST
00053 n = 1;
00054 if (setsockopt(e->fd, SOL_SOCKET, SO_BROADCAST, &n,
00055 sizeof(n)) < 0)
00056 return (eth_close(e));
00057 #endif
00058 strlcpy(e->ifr.ifr_name, device, sizeof(e->ifr.ifr_name));
00059
00060 if (ioctl(e->fd, SIOCGIFINDEX, &e->ifr) < 0)
00061 return (eth_close(e));
00062
00063 e->sll.sll_family = AF_PACKET;
00064 e->sll.sll_ifindex = e->ifr.ifr_ifindex;
00065 }
00066 return (e);
00067 }
00068
00069 ssize_t
00070 eth_send(eth_t *e, const void *buf, size_t len)
00071 {
00072 struct eth_hdr *eth = (struct eth_hdr *)buf;
00073
00074 e->sll.sll_protocol = eth->eth_type;
00075
00076 return (sendto(e->fd, buf, len, 0, (struct sockaddr *)&e->sll,
00077 sizeof(e->sll)));
00078 }
00079
00080 eth_t *
00081 eth_close(eth_t *e)
00082 {
00083 if (e != NULL) {
00084 if (e->fd >= 0)
00085 close(e->fd);
00086 free(e);
00087 }
00088 return (NULL);
00089 }
00090
00091 int
00092 eth_get(eth_t *e, eth_addr_t *ea)
00093 {
00094 struct addr ha;
00095
00096 if (ioctl(e->fd, SIOCGIFHWADDR, &e->ifr) < 0)
00097 return (-1);
00098
00099 if (addr_ston(&e->ifr.ifr_hwaddr, &ha) < 0)
00100 return (-1);
00101
00102 memcpy(ea, &ha.addr_eth, sizeof(*ea));
00103 return (0);
00104 }
00105
00106 int
00107 eth_set(eth_t *e, const eth_addr_t *ea)
00108 {
00109 struct addr ha;
00110
00111 ha.addr_type = ADDR_TYPE_ETH;
00112 ha.addr_bits = ETH_ADDR_BITS;
00113 memcpy(&ha.addr_eth, ea, ETH_ADDR_LEN);
00114
00115 addr_ntos(&ha, &e->ifr.ifr_hwaddr);
00116
00117 return (ioctl(e->fd, SIOCSIFHWADDR, &e->ifr));
00118 }