7 #define MIN(a, b) ((a) < (b) ? (a) : (b))
13 struct timeval timeout;
17 struct rawsock *rawsock_create(const char *interface, uint16_t protocol)
19 char buf[PCAP_ERRBUF_SIZE];
20 struct bpf_program fp;
24 sock = malloc(sizeof(struct rawsock));
32 sock->pcap = pcap_open_live(interface, BUFSIZ, 1, 1, buf);
34 fprintf(stderr, "pcap_open_live: %s\n", buf);
39 fprintf(stderr, "Warning: %s.\n", buf);
42 if (pcap_datalink(sock->pcap) != DLT_EN10MB) {
43 fprintf(stderr, "Interface %s not supported.\n", interface);
47 sock->fd = pcap_get_selectable_fd(sock->pcap);
49 fprintf(stderr, "No selectable file descriptor available.\n");
53 snprintf(buf, sizeof(buf), "ether proto %04x", protocol);
54 err = pcap_compile(sock->pcap, &fp, buf, 0, PCAP_NETMASK_UNKNOWN);
56 pcap_perror(sock->pcap, "pcap_compile");
60 if ((err = pcap_setfilter(sock->pcap, &fp))) {
61 pcap_perror(sock->pcap, "pcap_setfilter");
68 pcap_close(sock->pcap);
74 ssize_t rawsock_recv(struct rawsock *sock, void *buf, size_t len)
76 struct pcap_pkthdr* hdr;
81 if (sock->timeout.tv_sec || sock->timeout.tv_usec) {
83 FD_SET(sock->fd, &fds);
85 status = select(sock->fd + 1, &fds, NULL, NULL, &sock->timeout);
89 } else if (status == 0) {
94 status = pcap_next_ex(sock->pcap, &hdr, &capbuf);
97 memcpy(buf, capbuf, MIN(len, hdr->caplen));
102 pcap_perror(sock->pcap, "pcap_next_ex");
105 fprintf(stderr, "pcap_next_ex: returned %d.\n", status);
110 int rawsock_send(struct rawsock *sock, void *buf, size_t len)
112 #if defined(_WIN32) || defined(_WIN64)
113 if (pcap_sendpacket(sock->pcap, buf, len) == 0) {
116 pcap_perror(sock->pcap, "pcap_sendpacket");
120 if (pcap_inject(sock->pcap, buf, len) == len) {
123 pcap_perror(sock->pcap, "pcap_inject");
129 int rawsock_close(struct rawsock *sock)
131 pcap_close(sock->pcap);
136 int rawsock_set_timeout(struct rawsock *sock, unsigned msec)
138 sock->timeout.tv_sec = msec / 1000;
139 sock->timeout.tv_usec = (msec % 1000) * 1000;