| 网站首页 | 业界新闻 | 小组 | 威客 | 人才 | 下载频道 | 博客 | 代码贴 | 在线编程 | 编程论坛
欢迎加入我们,一同切磋技术
用户名:   
 
密 码:  
共有 4462 人关注过本帖
标题:找到的第一个用pcap的小程序
只看楼主 加入收藏
madfrogme
Rank: 16Rank: 16Rank: 16Rank: 16
等 级:版主
威 望:21
帖 子:1160
专家分:1106
注 册:2009-6-24
结帖率:98.63%
收藏
 问题点数:0 回复次数:0 
找到的第一个用pcap的小程序
一个打印网卡,network address , network mask 的小程序

程序代码:
#include <stdio.h>
#include <stdlib.h>
#include <pcap.h>
#include <errno.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>

int main(int argc, char **argv) {
    char *dev; /* name of the device to use */
    char *net; /* dot notation of the network address*/
    char *mask; /* dot notation of the network mask*/
    int ret;
    char errbuf[PCAP_ERRBUF_SIZE];
    bpf_u_int32 netp; /* ip */
    bpf_u_int32 maskp; /* subnet mask */
    struct in_addr addr;

    /* ask pcap to find a valid device for use to sniff on */
    dev = pcap_lookupdev(errbuf);

    /*error checking */
    if(dev == NULL) {
        printf("%s\n",errbuf);
        exit(1);
    }

    /* print out device name */
    printf("DEV: %s\n",dev);

    /* ask pcap for the network address and mask of the device */
    ret = pcap_lookupnet(dev, &netp, &maskp, errbuf);
    if(ret == -1) {
        printf("%s\n",errbuf);
        exit(1);
    }

    addr.s_addr = netp;
    net = inet_ntoa(addr);

    if(net == NULL) {
        perror("inet_ntoa");
        exit(1);
    }
    printf("NET: %s\n",net);

    addr.s_addr = maskp;
    mask = inet_ntoa(addr);

    if(mask == NULL) {
        perror("inet_ntoa");
        exit(1);
    }
    printf("MASK: %s\n",mask);
    
    return 0;
}


编译的时候是
$ gcc -lpcap -o capture capture.c

执行的时候要用root,否则没反应
$ sudo ./capture

注一下in_addr 结构体提醒
#include <netinet/in.h>

struct sockaddr_in {
    short            sin_family;   // e.g. AF_INET
    unsigned short   sin_port;     // e.g. htons(3490)
    struct in_addr   sin_addr;     // see struct in_addr, below
    char             sin_zero[8];  // zero this if you want to
};

struct in_addr {
    unsigned long s_addr;  // load with inet_aton()
};


[ 本帖最后由 madfrogme 于 2012-8-9 21:12 编辑 ]
搜索更多相关主题的帖子: mask network address include 
2012-08-09 20:09
快速回复:找到的第一个用pcap的小程序
数据加载中...
 
   



关于我们 | 广告合作 | 编程中国 | 清除Cookies | TOP | 手机版

编程中国 版权所有,并保留所有权利。
Powered by Discuz, Processed in 0.014162 second(s), 8 queries.
Copyright©2004-2024, BCCN.NET, All Rights Reserved