荔园在线
荔园之美,在春之萌芽,在夏之绽放,在秋之收获,在冬之沉淀
[回到开始]
[上一篇][下一篇]
发信人: gon.bbs@bbs.cqupt.edu.cn (人浮于世), 信区: Linux
标 题: 转贴一个程序
发信站: 幽幽黄桷兰 (Fri May 2 18:23:36 2003)
转信站: SZU!news.tiaozhan.com!news.happynet.org!CQUPT
网络数据的捕获
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <linux/if_ether.h>
#include <netinet/ip.h>
#include <sys/ioctl.h>
#include <net/if.h>
#define __FAVOR_BSD
#include <netinet/tcp.h>
#include <netinet/udp.h>
#undef __FAVOR_BSD
#include <netinet/in.h>
#include <errno.h>
#include <string.h>
#define SIZE 1500
char dotted[16];
void print_mac(struct ethhdr *);
const char *print_ip(struct in_addr *);
int main()
{
int sockfd;
char buf[SIZE];
struct sockaddr_in cliaddr;
int clilen;
unsigned long count = 0;
struct ifreq ifr;
char device[] = "eth1";
struct ethhdr *ethhdr;
struct ip *ip;
int hiplen;
struct tcphdr *tcp;
struct udphdr *udp;
errno = 0;
if((sockfd=socket(AF_INET, SOCK_PACKET, htons(ETH_P_ALL))) == -1) {
//if((sockfd=socket(AF_INET, SOCK_PACKET, htons(ETH_P_IP))) == -1) {
perror("socket");
exit(1);
}
strcpy(ifr.ifr_name, device);
if(ioctl(sockfd, SIOCGIFFLAGS, &ifr) == -1) {
perror("ioctl");
exit(1);
}
ifr.ifr_flags |= IFF_PROMISC;
if(ioctl(sockfd, SIOCSIFFLAGS, &ifr) == -1) {
perror("ioctl");
exit(1);
}
while(1) {
memset(buf, 0, sizeof(buf));
clilen = sizeof(struct sockaddr_in);
if(recvfrom(sockfd, buf, sizeof(buf), 0, (struct sockaddr *)&cliaddr
, &c
lilen) < 0) {
perror("recvfrom");
exit(1);
}
printf("##%ld ", count++);
//generally it's ether frame
ethhdr = (struct ethhdr *)buf;
print_mac(ethhdr);
if(ethhdr->h_proto != htons(ETH_P_IP))
continue;
ip = (struct ip *)(buf + 14);
printf("\tSource ip: %s, ", print_ip(&ip->ip_src));
printf("Dest ip: %s\n", print_ip(&ip->ip_dst));
hiplen = ip->ip_hl << 2;
if(ip->ip_p == IPPROTO_TCP) {
tcp = (struct tcphdr *)(buf+ 14 + hiplen);
printf("\ttcp packet, source port %d, dest port %d\n",
ntohs(tcp->th_sport),
ntohs(tcp->th_dport));
} else if(ip->ip_p == IPPROTO_UDP) {
udp = (struct udphdr *)(buf + 14 + hiplen);
printf("\tudp packet, source port %d, dest port %d\n",
ntohs(udp->uh_sport),
ntohs(udp->uh_dport));
} else {
printf("\tunknown protocol: %d\n", ip->ip_p);
}
}
}
void print_mac(struct ethhdr *eth)
{
unsigned char *d, *s;
unsigned short proto;
d = eth->h_dest;
s = eth->h_source;
proto = ntohs(eth->h_proto);
printf("Src MAC: %x:%x:%x:%x:%x:%x, Dst MAC: %x:%x:%x:%x:%x:%x, proto 0x
%04x
\n", s[0], s[1], s[2], s[3], s[4], s[5], d[0], d[1], d[2], d[3], d[4], d[5],
pro
to);
return;
}
const char *print_ip(struct in_addr *addr)
{
memset(dotted, 0, sizeof(dotted));
return (inet_ntop(AF_INET, addr, dotted, sizeof(dotted)));
}
--
※ 来源:·幽幽黄桷兰 bbs.cqupt.edu.cn·[FROM: missyou.net]
[回到开始]
[上一篇][下一篇]
荔园在线首页 友情链接:深圳大学 深大招生 荔园晨风BBS S-Term软件 网络书店