*程序功能:對捕獲的數據包只輸出網絡訪問層報頭為以太祯 網際層報頭為ip4 傳輸層報頭為tcp的 源目的主機的,mac地址,ip地址,端口號*/
*程序功能:對捕獲的數據包只輸出網絡訪問層報頭為以太祯 網際層報頭為ip4 傳輸層報頭為tcp的 源目的主機的,mac地址,ip地址,端口號*/
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pcap.h>
#include <netinet/if_ether.h>
#define IP 2048
#define TCP 6
typedef unsigned char UINT1;
typedef unsigned short UINT2;
typedef unsigned int UINT4;
typedef struct ether
{
UINT1 dest[6];
UINT1 src[6];
UINT2 proto;
UINT1 data[0];
} tEther;
typedef struct ip
{
UINT1 hlen; /*首部長度+版本 */
UINT1 tos; /*服務 */
UINT2 len; /*總長度 */
UINT2 ipid; /*標示 */
UINT2 flagoff; /*標示加偏移 */
UINT1 ttl; /*生存時間 */
UINT1 proto; /*協議 */
UINT2 cksum; /*首部檢驗和 */
UINT4 src; /*源地址 */
UINT4 dest; /*目地地址 */
UINT1 data[0];
} tIp;
typedef struct tcp
{
UINT2 sport;
UINT2 dport;
UINT4 seq;
UINT4 ack;
UINT1 hlen;
UINT1 code;
UINT2 window;
UINT2 chsum;
UINT2 urg;
char data[0];
} tTcp;
void proc_pkt (u_char * user, const struct pcap_pkthdr *hp,
const u_char * packet);
void net_host (UINT4 ipaddr);
int
main ()
{
char *dev = NULL;
pcap_t *descr;
struct pcap_pkthdr hdr;
u_char *packet;
char errbuf[PCAP_ERRBUF_SIZE];
int promisc = 0, cnt = 5;
int pcap_time_out = 100;
struct tEther *pEpkt;
UINT4 net, mask;
dev = pcap_lookupdev (errbuf);
pcap_lookupnet (dev, &net, &mask, errbuf);
descr = pcap_open_live (dev, BUFSIZ, promisc, pcap_time_out, errbuf);
printf ("網絡號:");
net_host (net);
printf ("網絡掩碼:");
net_host (mask);
printf ("\n\n");
pcap_loop (descr, -1, proc_pkt, NULL);
printf ("%s\n", dev);
return 0;
}
void
proc_pkt (u_char * user, const struct pcap_pkthdr *hp, const u_char * packet)
{
tEther *pEther;
tIp *pIp;
int i;
pEther = (tEther *) packet;
if (ntohs (pEther->proto) == IP) /*網絡層的報頭為IP*/
{
pIp = (tIp *) pEther->data;
if (pIp->proto == TCP) /*傳輸層的報頭為為tcp */
{
tTcp *pTcp;
pTcp = (tTcp *) pIp->data;
printf ("目的MAC地址:");
for (i = 0; i < 6; i++)
{
if ((pEther->dest[i]) < 16)
printf ("0");
printf ("%x ", pEther->dest[i]);
}
printf ("\n源MAC地址:");
for (i = 0; i < 6; i++)
{
if (((pEther->src[i]) < 16))
printf ("0");
printf ("%x ", pEther->src[i]);
}
printf ("\n");
printf ("源IP地址:");
net_host (pIp->src);
printf ("目的IP地址:");
net_host (pIp->dest);
printf ("源端口:");
printf ("%hu\n", ntohs (pTcp->sport));
printf ("目的端口:");
printf ("%hu\n\n\n", ntohs (pTcp->dport));
}
}
return;
}
void
net_host (UINT4 ip_mask) /*將網絡字節序的ip地址以及網絡掩碼轉換轉化為人們常用的形式 */
{
UINT4 one, two, three, four;
one = ip_mask;
one = one >> 24;
two = ip_mask;
two = two >> 16;
two = two & 0xff;
three = ip_mask;
three = three >> 8;
three = three & 0xff;
four = ip_mask;
four = four & 0xff;
printf ("%u.%u.%u.%u\n", four, three, two, one);
}
作者“programmer”