• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

C++ pcap_setnonblock函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了C++中pcap_setnonblock函数的典型用法代码示例。如果您正苦于以下问题:C++ pcap_setnonblock函数的具体用法?C++ pcap_setnonblock怎么用?C++ pcap_setnonblock使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了pcap_setnonblock函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的C++代码示例。

示例1: pcap_ex_setnonblock

void
pcap_ex_setnonblock(pcap_t *pcap, int nonblock, char *ebuf)
{
#ifdef HAVE_PCAP_SETNONBLOCK
	pcap_setnonblock(pcap, nonblock, ebuf);
#endif
}
开发者ID:WilenceYao,项目名称:pypcap,代码行数:7,代码来源:pcap_ex.c


示例2: pcap_open

struct pcap_port *
pcap_open(struct pcap_port *pcap_port) {
    char errbuf[PCAP_ERRBUF_SIZE];
    struct pcap_drv *pcap_drv = pcap_port->drv;

    pcap_t *pcap = NULL;
    pcap = pcap_open_live(pcap_port->name, PCAP_SNAPLEN, true/*promisc*/, -1/*to_ms*/, errbuf);
    if (pcap == NULL) {
        logger_log(pcap_drv->logger, LOG_ERR, "Unable to open device %s: %s.", pcap_port->name, errbuf);
        return NULL;
    }

    if(pcap_setnonblock(pcap, true, errbuf) != 0) {
        logger_log(pcap_drv->logger, LOG_ERR, "Unable to set device to promisc %s: %s.", pcap_port->name, errbuf);
        return NULL;
    }

    if(pcap_setdirection(pcap, PCAP_D_IN) != 0) {
        logger_log(pcap_drv->logger, LOG_ERR, "Unable to set device direction %s: %s.", pcap_port->name, pcap_geterr(pcap));
        return NULL;
    }

    pcap_port->pcap    = pcap;
    pcap_port->fd      = pcap_fileno(pcap);

    pcap_port->watcher = malloc(sizeof(ev_io));
    pcap_port->watcher->data = pcap_port;
    ev_io_init(pcap_port->watcher, event_loop_packet_in_cb, pcap_port->fd, EV_READ);
    pcap_port_fill(pcap_port);

    return pcap_port;
}
开发者ID:elekjani,项目名称:ofss,代码行数:32,代码来源:pcap_port.c


示例3: add_device

static void
add_device(orchids_t *ctx, mod_entry_t *mod, config_directive_t *dir)
{

  /*  dev: the network device to open
      capd: a packet capture descriptor
   */

  int fd;
  char* dev;
  char errbuf[PCAP_ERRBUF_SIZE]="";
  pcap_t* capd = NULL;

  dev = dir->args;
  DebugLog(DF_MOD, DS_INFO, "Add 802.11 listen device %s\n", dev);

  capd = pcap_open_live(dev, 65535, 1, 1, errbuf);

  if ( strlen(errbuf) != 0 ) {
    DebugLog(DF_MOD, DS_ERROR, "pcap_open_live error: %s\n", errbuf);
    return;
  }

  pcap_setnonblock(capd, 1, NULL);
  fd = pcap_fileno(capd);
  datalink_type = pcap_datalink(capd);

  add_input_descriptor(ctx, mod, wifi_callback, fd, capd);
}
开发者ID:triplekill,项目名称:orchids,代码行数:29,代码来源:mod_wifi.c


示例4: prvConfigureCaptureBehaviour

static void prvConfigureCaptureBehaviour( void )
{
    struct bpf_program xFilterCode;
    const long lMinBytesToCopy = 10L, lBlocking = 1L;
    unsigned long ulNetMask;

    /* Unblock a read as soon as anything is received. */
    pcap_setmintocopy( pxOpenedInterfaceHandle, lMinBytesToCopy );

    /* Allow blocking. */
    pcap_setnonblock( pxOpenedInterfaceHandle, lBlocking, cErrorBuffer );

    /* Set up a filter so only the packets of interest are passed to the lwIP
    stack.  cErrorBuffer is used for convenience to create the string.  Don't
    confuse this with an error message. */
    sprintf( cErrorBuffer, "broadcast or multicast or host %d.%d.%d.%d", configIP_ADDR0, configIP_ADDR1, configIP_ADDR2, configIP_ADDR3 );

    ulNetMask = ( configNET_MASK3 << 24UL ) | ( configNET_MASK2 << 16UL ) | ( configNET_MASK1 << 8L ) | configNET_MASK0;

    if( pcap_compile(pxOpenedInterfaceHandle, &xFilterCode, cErrorBuffer, 1, ulNetMask ) < 0 ) {
        printf( "\r\nThe packet filter string is invalid\r\n" );
    } else {
        if( pcap_setfilter( pxOpenedInterfaceHandle, &xFilterCode ) < 0 ) {
            printf( "\r\nAn error occurred setting the packet filter.\r\n" );
        }
    }

    /* Create a task that simulates an interrupt in a real system.  This will
    block waiting for packets, then send a message to the uIP task when data
    is available. */
    xTaskCreate( prvInterruptSimulator, "MAC_ISR", configMINIMAL_STACK_SIZE, NULL, configMAC_ISR_SIMULATOR_PRIORITY, NULL );
}
开发者ID:peterliu2,项目名称:FreeRTOS,代码行数:32,代码来源:ethernetif.c


示例5: tc_pcap_socket_in_init

int
tc_pcap_socket_in_init(pcap_t **pd, char *device, 
        int snap_len, int buf_size, char *pcap_filter)
{
    int         fd;
    char        ebuf[PCAP_ERRBUF_SIZE]; 
    struct      bpf_program fp;
    bpf_u_int32 net, netmask;      

    if (device == NULL) {
        return TC_INVALID_SOCK;
    }

    tc_log_info(LOG_NOTICE, 0, "pcap open,device:%s", device);

    *ebuf = '\0';

    if (tc_pcap_open(pd, device, snap_len, buf_size) == TC_ERR) {
        return TC_INVALID_SOCK;
    }

    if (pcap_lookupnet(device, &net, &netmask, ebuf) < 0) {
        net = 0;
        netmask = 0;
        tc_log_info(LOG_WARN, 0, "lookupnet:%s", ebuf);
        return TC_INVALID_SOCK;
    }

    if (pcap_compile(*pd, &fp, pcap_filter, 0, netmask) == -1) {
        tc_log_info(LOG_ERR, 0, "couldn't parse filter %s: %s", 
                pcap_filter, pcap_geterr(*pd));
        return TC_INVALID_SOCK;
    }

    if (pcap_setfilter(*pd, &fp) == -1) {
        tc_log_info(LOG_ERR, 0, "couldn't install filter %s: %s",
                pcap_filter, pcap_geterr(*pd));
        pcap_freecode(&fp);
        return TC_INVALID_SOCK;
    }

    pcap_freecode(&fp);

    if (pcap_get_selectable_fd(*pd) == -1) {
        tc_log_info(LOG_ERR, 0, "pcap_get_selectable_fd fails"); 
        return TC_INVALID_SOCK;
    }

    if (pcap_setnonblock(*pd, 1, ebuf) == -1) {
        tc_log_info(LOG_ERR, 0, "pcap_setnonblock failed: %s", ebuf);
        return TC_INVALID_SOCK;
    }

    fd = pcap_get_selectable_fd(*pd);

    return fd;
}
开发者ID:343829084,项目名称:tcpcopy,代码行数:57,代码来源:tc_socket.c


示例6: tc_pcap_socket_in_init

int
tc_pcap_socket_in_init(pcap_t **pd, char *device, char *pcap_filter)
{
    int         fd;
    char        ebuf[PCAP_ERRBUF_SIZE]; 
    struct      bpf_program fp;
    bpf_u_int32 net, netmask;      

    if (device == NULL) {
        return TC_INVALID_SOCKET;
    }

    tc_log_info(LOG_NOTICE, 0, "pcap open,device:%s", device);

    *ebuf = '\0';
    *pd = pcap_open_live(device, PCAP_RECV_BUF_SIZE, 0, 1000, ebuf);
    if (*pd == NULL) {
        tc_log_info(LOG_ERR, 0, "pcap error:%s", ebuf);
        return TC_INVALID_SOCKET;
    } else if (*ebuf) {
        tc_log_info(LOG_WARN, 0, "pcap warn:%s", ebuf);
    }

    if (pcap_lookupnet(device, &net, &netmask, ebuf) < 0) {
        net = 0;
        netmask = 0;
        tc_log_info(LOG_WARN, 0, "lookupnet:%s", ebuf);
    }

    if (pcap_compile(*pd, &fp, pcap_filter, 0, netmask) == -1) {
        tc_log_info(LOG_ERR, 0, "couldn't parse filter %s: %s", 
                pcap_filter, pcap_geterr(*pd));
        return TC_INVALID_SOCKET;
    }

    if (pcap_setfilter(*pd, &fp) == -1) {
        tc_log_info(LOG_ERR, 0, "couldn't install filter %s: %s",
                pcap_filter, pcap_geterr(*pd));
        return TC_INVALID_SOCKET;
    }

    if (pcap_get_selectable_fd(*pd) == -1) {
        tc_log_info(LOG_ERR, 0, "pcap_get_selectable_fd fails"); 
        return TC_INVALID_SOCKET;
    }

    if (pcap_setnonblock(*pd, 1, ebuf) == -1) {
        tc_log_info(LOG_ERR, 0, "pcap_setnonblock failed: %s", ebuf);
        return TC_INVALID_SOCKET;
    }

    fd = pcap_get_selectable_fd(*pd);

    return fd;
}
开发者ID:changguanghua,项目名称:tcpcopy,代码行数:55,代码来源:tc_socket.c


示例7: main

int main(int argc, char *argv[])
{
	char *dev, errbuf[PCAP_ERRBUF_SIZE];
	pcap_t *handle;
	int selectable_fd;

	if (argc == 2) {
		dev = argv[1];
	} else {
		dev = pcap_lookupdev(errbuf);
	}

	if (dev == NULL) {
		fprintf(stderr, "Couldn't find default device: %s\n", errbuf);
		return (2);
	}

	handle = pcap_open_live(dev, BUFSIZ, 1, 0, errbuf);
	if (handle == NULL) {
		fprintf(stderr, "Couldn't open device %s: %s\n", dev, errbuf);
		return (2);
	}

	if (pcap_datalink(handle) != DLT_EN10MB) {
		fprintf(stderr, "Device %s doesn't provide Ethernet headers - "
		                "not supported\n",
		        dev);
		return (2);
	}

	if (pcap_setnonblock(handle, 1, errbuf) != 0) {
		fprintf(stderr, "Non-blocking mode failed: %s\n", errbuf);
		return (2);
	}

	selectable_fd = pcap_get_selectable_fd(handle);
	if (-1 == selectable_fd) {
		fprintf(stderr, "pcap handle not selectable.\n");
		return (2);
	}

	init_curses();
	mvprintw(0, 0, "Device: %s\n", dev);

	grab_packets(selectable_fd, handle);

	/* And close the session */
	pcap_close(handle);
	return 0;
}
开发者ID:tcharding,项目名称:toptalk,代码行数:50,代码来源:main.c


示例8: p_setnonblock

static PyObject * p_setnonblock (PyObject *self, PyObject *args)
{
  pcap_t * ppcap;
  int nonblock;
  char errbuf[PCAP_ERRBUF_SIZE];

  if (!PyArg_ParseTuple(args, "li", (long*)&ppcap, (int*)&nonblock)) return NULL;
  if (pcap_setnonblock(ppcap, nonblock ? 1 : 0, errbuf) == -1)
  {
    PyErr_SetString(PyExc_RuntimeError, errbuf);
    return NULL;
  }

  Py_RETURN_NONE;
}
开发者ID:14gr1010,项目名称:software,代码行数:15,代码来源:pxpcap.cpp


示例9: mi_alloc

struct mif *mi_open(char *iface)
{
    struct mif *mi;
    struct priv_if *pi;
    pcap_t *pkt_in, *pkt_out;
    char errbuf[PCAP_ERRBUF_SIZE];

    /* setup mi struct */
    mi = mi_alloc(sizeof(*pi));
    if (!mi)
        return NULL;

    mi->read  = mi_read;
    mi->write = mi_write;
    mi->close = mi_close;

    // for pkt in
    pkt_in = pcap_open_live(iface, 4096, 1, 10, errbuf);
    if (pkt_in == NULL) {
        printf("Unable to open interface %s in pcap: %s\n", iface, errbuf);
        return NULL;
    }

    if (pcap_datalink(pkt_in) != DLT_IEEE802_11_RADIO) {
        printf("Device %s doesn't provide 80211 radiotap header\n", iface);
        return NULL;
    }

    if (pcap_setnonblock(pkt_in, 1, errbuf) == -1) {
        printf("Device %s doesn't set non-blocking mode\n", iface);
        return NULL;
    }

    // for pkt out
    pkt_out = pcap_open_live(iface, 4096, 1, 10, errbuf);
    if (pkt_out == NULL) {
        printf("Unable to open interface %s in pcap: %s\n", iface, errbuf);
        return NULL;
    }

    pi = mi_priv(mi);
    pi->fd_in = pkt_in;
    pi->fd_out = pkt_out;

    return mi;
}
开发者ID:teddyyy,项目名称:libfcap,代码行数:46,代码来源:interface.c


示例10: pcap_init

void pcap_init(void)
{
    //char *dev;
    char err_buff[PCAP_ERRBUF_SIZE];

    if (dev == NULL) {
        // 1. find the active interface for capturing data
        if ((dev = pcap_lookupdev(err_buff)) == NULL) {
            fprintf(stderr, "Couldn't find default device: %s\n", err_buff);
            exit(EXIT_FAILURE);
        }
    }

    // 2. open the interface
    bpf_u_int32 net, mask;

    if ((pcap_dest = pcap_open_live(dev, SNAP_LEN, 0, 1000, err_buff)) == NULL){
        fprintf(stderr, "Failed to open the device %s\n", dev);
        exit(EXIT_FAILURE);
    }

    if (pcap_lookupnet(dev, &net, &mask, err_buff) == -1) {
        fprintf(stderr, "Failed to get net.\n");
        exit(EXIT_FAILURE);
    }

    // 3. complie the filter
    char filter[] = "ip";
    struct bpf_program fp;
    if (pcap_compile(pcap_dest, &fp, filter, 0, net) == -1) {
        fprintf(stderr, "failed to compile the filter %s: %s\n",
                                                filter, pcap_geterr(pcap_dest));
        exit(EXIT_FAILURE);
    }

    if (pcap_setfilter(pcap_dest, &fp) == -1) {
        fprintf(stderr, "failed to set filter %s: %s\n", filter,
                                                        pcap_geterr(pcap_dest));
        exit(EXIT_FAILURE);
    }

    // 4. set the mode of pcap as non-block
    if ((pcap_setnonblock(pcap_dest, 1, err_buff)) != 0) {
        fprintf(stderr, "\e\[31m[Error]\e\[0m: %s\n", err_buff);
        exit(EXIT_FAILURE);
    }
开发者ID:huiliu,项目名称:sniffer.network,代码行数:46,代码来源:pcap.c


示例11: PyErr_SetString

static PyObject *ppcap_setnonblock(ppcap *self, PyObject *args)
{
    int nonblock, retval;
    char errbuf[PCAP_ERRBUF_SIZE];

    if (!PyArg_ParseTuple(args, "i", &nonblock))
        return NULL;
    if (!ppcap_isset_handle(self->handle)) {
        PyErr_SetString(PyExc_Ppcap, "pcap handle is not created.");
        return NULL;
    }
    retval = pcap_setnonblock(self->handle, nonblock, errbuf);
    if (retval == -1) {
        PyErr_Format(PyExc_Ppcap, "%s", errbuf);
        return NULL;
    }
    Py_RETURN_NONE;
}
开发者ID:Magnus9,项目名称:_packet,代码行数:18,代码来源:ppcap.c


示例12: pcap_findalldevs

ebbrt::RawSocket::RawSocket()
{
  char errbuf[PCAP_ERRBUF_SIZE];
  pcap_if_t* alldevs;

  int ret = pcap_findalldevs(&alldevs, errbuf);
  assert(ret != -1);

  while (alldevs != NULL) {
    if (strcmp(alldevs->name, dev) == 0) {
      break;
    }
    alldevs = alldevs->next;
  }

  assert(alldevs != NULL);

  auto addr = alldevs->addresses;
  while (addr != NULL) {
    if (addr->addr->sa_family == AF_PACKET) {
      break;
    }
    addr = addr->next;
  }
  assert(addr != NULL);

  auto packet_addr = reinterpret_cast<struct sockaddr_ll*>(addr->addr);
  std::copy(&packet_addr->sll_addr[0], &packet_addr->sll_addr[5], mac_addr_);

  pdev_ = pcap_open_live(dev, 65535, 0, 0, errbuf);
  assert(dev != NULL);

  ret = pcap_setnonblock(pdev_, 1, errbuf);
  assert(ret != -1);

  int fd = pcap_get_selectable_fd(pdev_);
  assert(fd != -1);

  uint8_t interrupt = event_manager->AllocateInterrupt([]() {
      ethernet->Receive();
    });
  event_manager->RegisterFD(fd, EPOLLIN, interrupt);
}
开发者ID:B-Rich,项目名称:EbbRT,代码行数:43,代码来源:RawSocket.cpp


示例13: pcap_event_init

void
pcap_event_init(client_conn_t * conn)
{
    struct bpf_program filterp;
    bpf_u_int32     maskp,
                    netp;
    char            errbuf[PCAP_ERRBUF_SIZE];

    if (pcap_lookupnet(conn->start_header.dev, &netp, &maskp, errbuf) < 0)
	goto pcap_err;

    if ((conn->descr =
	 pcap_open_live(conn->start_header.dev,
			conn->start_header.snaplen, 1, 100,
			errbuf)) == NULL)
	goto pcap_err;

    if (conn->start_header.bpf != NULL) {
	if (pcap_compile(conn->descr, &filterp,
			 conn->start_header.bpf, 0, netp) < 0)
	    goto pcap_err;

	pcap_setfilter(conn->descr, &filterp);
    }

    if (pcap_setnonblock(conn->descr, 1, errbuf) < 0)
	goto pcap_err;

    if ((conn->pcap_fd = pcap_get_selectable_fd(conn->descr)) <= 0)
	goto pcap_err;

    event_set(&conn->pcap_event, conn->pcap_fd,
	      EV_READ | EV_PERSIST, (void *) pcap_driver, (void *) conn);
    event_add(&conn->pcap_event, 0);
    return;

  pcap_err:
    LOG("pcap err %s\n", errbuf);
    free_client_conn(conn);
    return;
}
开发者ID:WilliamSalusky,项目名称:rpcap,代码行数:41,代码来源:rpcap-server.c


示例14: hijack_open

/**
 * Open pcap device
 *
 */
static int hijack_open ( const char *interface, struct hijack *hijack ) {
    char errbuf[PCAP_ERRBUF_SIZE];

    /* Open interface via pcap */
    errbuf[0] = '\0';
    hijack->pcap = pcap_open_live ( interface, SNAPLEN, 1, 0, errbuf );
    if ( ! hijack->pcap ) {
        logmsg ( LOG_ERR, "Failed to open %s: %s\n",
                 interface, errbuf );
        goto err;
    }
    if ( errbuf[0] )
        logmsg ( LOG_WARNING, "Warning: %s\n", errbuf );

    /* Set capture interface to non-blocking mode */
    if ( pcap_setnonblock ( hijack->pcap, 1, errbuf ) < 0 ) {
        logmsg ( LOG_ERR, "Could not make %s non-blocking: %s\n",
                 interface, errbuf );
        goto err;
    }

    /* Get file descriptor for select() */
    hijack->fd = pcap_get_selectable_fd ( hijack->pcap );
    if ( hijack->fd < 0 ) {
        logmsg ( LOG_ERR, "Cannot get selectable file descriptor "
                 "for %s\n", interface );
        goto err;
    }

    /* Get link layer type */
    hijack->datalink = pcap_datalink ( hijack->pcap );

    return 0;

err:
    if ( hijack->pcap )
        pcap_close ( hijack->pcap );
    return -1;
}
开发者ID:B-Rich,项目名称:serialice,代码行数:43,代码来源:hijack.c


示例15: create_ether_device

ether_device *
create_ether_device( const char *name, const size_t max_send_queue, const size_t max_recv_queue ) {
    assert( name != NULL );
    assert( strlen( name ) > 0 );
    assert( max_send_queue > 0 );
    assert( max_recv_queue > 0 );

    int nfd = socket( PF_INET, SOCK_DGRAM, 0 );
    if ( nfd < 0 ) {
        char error_string[ ERROR_STRING_SIZE ];
        error( "Failed to open a socket ( ret = %d, errno = %s [%d] ).",
               nfd, safe_strerror_r( errno, error_string, sizeof( error_string ) ), errno );
        return NULL;
    }

    struct ifreq ifr;
    memset( &ifr, 0, sizeof( ifr ) );
    strncpy( ifr.ifr_name, name, IFNAMSIZ );
    ifr.ifr_name[ IFNAMSIZ - 1 ] = '\0';
    int ret = ioctl( nfd, SIOCGIFINDEX, &ifr );
    if ( ret == -1 ) {
        char error_string[ ERROR_STRING_SIZE ];
        error( "Failed to retrieve an interface index of %s ( ret = %d, errno = %s [%d] ).",
               name, ret, safe_strerror_r( errno, error_string, sizeof( error_string ) ), errno );
        close( nfd );
        return NULL;
    }
    int ifindex = ifr.ifr_ifindex;

    ret = ioctl( nfd, SIOCGIFMTU, &ifr );
    if ( ret == -1 ) {
        char error_string[ ERROR_STRING_SIZE ];
        error( "Failed to retrieve MTU of %s ( ret = %d, errno = %s [%d] ).",
               name, ret, safe_strerror_r( errno, error_string, sizeof( error_string ) ), errno );
        close( nfd );
        return NULL;
    }
    int mtu = ifr.ifr_mtu;

    ret = ioctl( nfd, SIOCGIFHWADDR, &ifr );
    if ( ret == -1 ) {
        char error_string[ ERROR_STRING_SIZE ];
        error( "Failed to retrieve hardware address of %s ( ret = %d, error = %s [%d] ).",
               name, ret, safe_strerror_r( errno, error_string, sizeof( error_string ) ), errno );
        close( nfd );
        return NULL;
    }

    close( nfd );

    size_t device_mtu = ( size_t ) mtu + MAX_L2_HEADER_LENGTH;
#ifdef WITH_PCAP
    char errbuf[ PCAP_ERRBUF_SIZE ];
    pcap_t *handle = pcap_open_live( name, ( int ) device_mtu, 1, 100, errbuf );
    if( handle == NULL ) {
        error( "Failed to open %s ( %s ).", name, errbuf );
        return NULL;
    }
    if ( pcap_setnonblock( handle, 1, errbuf ) == -1 ) {
        warn( "Failed to setnonblock %s ( %s ).", name, errbuf );
    }
    int fd = pcap_get_selectable_fd( handle );
#else // WITH_PCAP
    int fd = socket( PF_PACKET, SOCK_RAW, htons( ETH_P_ALL ) );
    if ( fd < 0 ) {
        char error_string[ ERROR_STRING_SIZE ];
        error( "Failed to open a socket ( ret = %d, errno = %s [%d] ).",
               fd, safe_strerror_r( errno, error_string, sizeof( error_string ) ), errno );
        return NULL;
    }

    struct sockaddr_ll sll;
    memset( &sll, 0, sizeof( sll ) );
    sll.sll_family = AF_PACKET;
    sll.sll_protocol = htons( ETH_P_ALL );
    sll.sll_ifindex = ifindex;
    ret = bind( fd, ( struct sockaddr * ) &sll, sizeof( sll ) );
    if ( ret < 0 ) {
        char error_string[ ERROR_STRING_SIZE ];
        error( "Failed to bind ( fd = %d, ret = %d, errno = %s [%d] ).",
               fd, ret, safe_strerror_r( errno, error_string, sizeof( error_string ) ), errno );
        close( fd );
        return NULL;
    }

    int val = TPACKET_V2;
    ret = setsockopt( fd, SOL_PACKET, PACKET_VERSION, &val, sizeof( val ) );
    if ( ret < 0 ) {
        char error_string[ ERROR_STRING_SIZE ];
        error( "Failed to set PACKET_VERSION to %d ( fd = %d, ret = %d, errno = %s [%d] ).",
               val, fd, ret, safe_strerror_r( errno, error_string, sizeof( error_string ) ), errno );
        close( fd );
        return NULL;
    }

    val = 1;
    ret = setsockopt( fd, SOL_PACKET, PACKET_AUXDATA, &val, sizeof( val ) );
    if ( ret < 0 ) {
        char error_string[ ERROR_STRING_SIZE ];
        error( "Failed to set PACKET_AUXDATA to %d ( fd = %d, ret = %d, errno = %s [%d] ).",
//.........这里部分代码省略.........
开发者ID:jemiam,项目名称:trema-edge,代码行数:101,代码来源:ether_device.c


示例16: l2_packet_init_libpcap

static int l2_packet_init_libpcap(struct l2_packet_data *l2,
				  unsigned short protocol)
{
	bpf_u_int32 pcap_maskp, pcap_netp;
	char pcap_filter[200], pcap_err[PCAP_ERRBUF_SIZE];
	struct bpf_program pcap_fp;

#ifdef CONFIG_WINPCAP
	char ifname[128];
	os_snprintf(ifname, sizeof(ifname), "\\Device\\NPF_%s", l2->ifname);
	pcap_lookupnet(ifname, &pcap_netp, &pcap_maskp, pcap_err);
	l2->pcap = pcap_open_live(ifname, 2500, 0, 10, pcap_err);
	if (l2->pcap == NULL) {
		fprintf(stderr, "pcap_open_live: %s\n", pcap_err);
		fprintf(stderr, "ifname='%s'\n", ifname);
		return -1;
	}
	if (pcap_setnonblock(l2->pcap, 1, pcap_err) < 0)
		fprintf(stderr, "pcap_setnonblock: %s\n",
			pcap_geterr(l2->pcap));
#else /* CONFIG_WINPCAP */
	pcap_lookupnet(l2->ifname, &pcap_netp, &pcap_maskp, pcap_err);
	l2->pcap = pcap_open_live(l2->ifname, 2500, 0, 10, pcap_err);
	if (l2->pcap == NULL) {
		fprintf(stderr, "pcap_open_live: %s\n", pcap_err);
		fprintf(stderr, "ifname='%s'\n", l2->ifname);
		return -1;
	}
	if (pcap_datalink(l2->pcap) != DLT_EN10MB &&
	    pcap_set_datalink(l2->pcap, DLT_EN10MB) < 0) {
		fprintf(stderr, "pcap_set_datalinke(DLT_EN10MB): %s\n",
			pcap_geterr(l2->pcap));
		return -1;
	}
#endif /* CONFIG_WINPCAP */
	os_snprintf(pcap_filter, sizeof(pcap_filter),
		    "not ether src " MACSTR " and "
		    "( ether dst " MACSTR " or ether dst " MACSTR " ) and "
		    "ether proto 0x%x",
		    MAC2STR(l2->own_addr), /* do not receive own packets */
		    MAC2STR(l2->own_addr), MAC2STR(pae_group_addr),
		    protocol);
	if (pcap_compile(l2->pcap, &pcap_fp, pcap_filter, 1, pcap_netp) < 0) {
		fprintf(stderr, "pcap_compile: %s\n", pcap_geterr(l2->pcap));
		return -1;
	}

	if (pcap_setfilter(l2->pcap, &pcap_fp) < 0) {
		fprintf(stderr, "pcap_setfilter: %s\n", pcap_geterr(l2->pcap));
		return -1;
	}

	pcap_freecode(&pcap_fp);
#ifdef BIOCIMMEDIATE
	/*
	 * When libpcap uses BPF we must enable "immediate mode" to
	 * receive frames right away; otherwise the system may
	 * buffer them for us.
	 */
	{
		unsigned int on = 1;
		if (ioctl(pcap_fileno(l2->pcap), BIOCIMMEDIATE, &on) < 0) {
			fprintf(stderr, "%s: cannot enable immediate mode on "
				"interface %s: %s\n",
				__func__, l2->ifname, strerror(errno));
			/* XXX should we fail? */
		}
	}
#endif /* BIOCIMMEDIATE */

#ifdef CONFIG_WINPCAP
	eloop_register_timeout(0, 100000, l2_packet_receive_timeout,
			       l2, l2->pcap);
#else /* CONFIG_WINPCAP */
	eloop_register_read_sock(pcap_get_selectable_fd(l2->pcap),
				 l2_packet_receive, l2, l2->pcap);
#endif /* CONFIG_WINPCAP */

	return 0;
}
开发者ID:qwerty1023,项目名称:wive-rtnl-firmware,代码行数:80,代码来源:l2_packet_pcap.c


示例17: nsock_pcap_open


//.........这里部分代码省略.........
    mp->pt = pcap_open_live((char* )pcap_device, snaplen, promisc, to_ms, err0r);
    if (mp->pt)  /* okay, opened!*/
      break;

    /* sorry, something failed*/
    if (++failed >= 3) {
      mp->pcap_device = strdup(pcap_device);
      fprintf(stderr,
              "Call to pcap_open_live(%s, %d, %d, %d) failed three times. Reported error: %s\n"
              "There are several possible reasons for this, depending on your operating system:\n"
              "LINUX: If you are getting Socket type not supported, try modprobe af_packet or recompile your kernel with PACKET enabled.\n"
              "*BSD:  If you are getting device not configured, you need to recompile your kernel with Berkeley Packet Filter support.  If you are getting No such file or directory, try creating the device (eg cd /dev; MAKEDEV <device>; or use mknod).\n"
              "*WINDOWS:  Nmap only supports ethernet interfaces on Windows for most operations because Microsoft disabled raw sockets as of Windows XP SP2.  Depending on the reason for this error, it is possible that the --unprivileged command-line argument will help.\n"
              "SOLARIS:  If you are trying to scan localhost and getting '/dev/lo0: No such file or directory', complain to Sun.  I don't think Solaris can support advanced localhost scans.  You can probably use \"-PN -sT localhost\" though.\n\n",
        pcap_device, snaplen, promisc, to_ms, err0r);
      return "nsock-pcap: can't open pcap! Are you root?";
    }

    fprintf(stderr,
            "pcap_open_live(%s, %d, %d, %d) FAILED. Reported error: %s. Will wait %d seconds then retry.\n",
            pcap_device, snaplen, promisc, to_ms, err0r, 4*failed);
    sleep(4* failed);
  } while (1);

  e = nsock_pcap_set_filter(mp->pt, pcap_device, bpf);
  if (e)
    return e;

#ifdef WIN32
  /* We want any responses back ASAP */
  pcap_setmintocopy(mp->pt, 1);
#endif

  mp->l3_offset = nsock_pcap_get_l3_offset(mp->pt, &datalink);
  mp->snaplen = snaplen;
  mp->datalink = datalink;
  mp->pcap_device = strdup(pcap_device);
#ifdef PCAP_CAN_DO_SELECT
  mp->pcap_desc = pcap_get_selectable_fd(mp->pt);
#else
  mp->pcap_desc = -1;
#endif
  mp->readsd_count = 0;

  /* Without setting this ioctl, some systems (BSDs, though it depends on the
   * release) will buffer packets in non-blocking mode and only return them in a
   * bunch when the buffer is full. Setting the ioctl makes each one be
   * delivered immediately. This is how Linux works by default. See the comments
   * surrounding the setting of BIOCIMMEDIATE in libpcap/pcap-bpf.c. */
#ifdef BIOCIMMEDIATE
  if (mp->pcap_desc != -1) {
    int immediate = 1;

    if (ioctl(mp->pcap_desc, BIOCIMMEDIATE, &immediate) < 0)
      fatal("Cannot set BIOCIMMEDIATE on pcap descriptor");
  }
#endif

  /* Set device non-blocking */
  if (pcap_setnonblock(mp->pt, 1, err0r) < 0) {
    /* I can't do select() on pcap! blocking + no_select is fatal */
    if(mp->pcap_desc < 0){
      Snprintf(errorbuf, sizeof(errorbuf),
               "nsock-pcap: Failed to set pcap descriptor on device %s to nonblocking state: %s",
               pcap_device, err0r);
      return errorbuf;
    }

    /* When we use bsd hack we also need to set non-blocking */
#ifdef PCAP_BSD_SELECT_HACK
    Snprintf(errorbuf, sizeof(errorbuf),
             "nsock-pcap: Failed to set pcap descriptor on device %s to nonblocking state: %s",
             pcap_device, err0r);
    return errorbuf;
#endif

    /* in other case, we can accept blocking pcap */
    fprintf(stderr, "Failed to set pcap descriptor on device %s to nonblocking state: %s",
            pcap_device, err0r);
  }

  if (ms->tracelevel > 0)
      nsock_trace(ms, "PCAP created successfully on device '%s' (pcap_desc=%i bsd_hack=%i to_valid=%i l3_offset=%i) (IOD #%li)",
      pcap_device,
      mp->pcap_desc,
#if PCAP_BSD_SELECT_HACK
      1,
#else
      0,
#endif
#if PCAP_RECV_TIMEVAL_VALID
      1,
#else
      0,
#endif
      mp->l3_offset,
      nsi->id);

  return NULL;
}
开发者ID:alex-chan,项目名称:nmap,代码行数:101,代码来源:nsock_pcap.c


示例18: main


//.........这里部分代码省略.........
    if (pcap_lookupnet(dev, &net, &mask, errbuf) == -1) {
        fprintf(stderr, "Couldn't get netmask for device %s: %s\n", dev, errbuf);
        net = 0;
        mask = 0;
    }

    struct ether_addr *ha = NULL;
    if ((ha = (struct ether_addr *) libnet_get_hwaddr(l)) == NULL) {
        fprintf(stderr, "%s", libnet_geterror(l));
        exit(EXIT_FAILURE);
    }

    // LLTP magic packet
    char* payload = "\x01\x00\x00\x00\xff\xff\xff\xff\xff\xff\x00\x00\x00\x00\x00\x00\x00\x00";
    char* hwdst   = "\xff\xff\xff\xff\xff\xff";

    memcpy(buf,payload,18);
    memcpy(buf+10, ha, 6);

    gettimeofday(&start_time, NULL);
    memcpy(buf+16, &start_time.tv_sec, 2); // emulate sequence number

    eth_ptag = libnet_build_ethernet(
                   hwdst, /* ethernet destination */
                   ha->ether_addr_octet,
                   /* ethernet source */
                   0x88d9,        /* protocol type */
                   buf,       /* payload */
                   18,    /* payload size */
                   l,     /* libnet handle */
                   0);    /* libnet id */
    if (eth_ptag == -1) {
        fprintf(stderr, "Can't build ethernet header: %s\n", libnet_geterror(l));
        libnet_destroy(l);
        exit(EXIT_FAILURE);
    }
    /*
     * Write it to the wire.
     */
    c = libnet_write(l);

    if (c == -1) {
        fprintf(stderr, "Write error: %s\n", libnet_geterror(l));
        libnet_destroy(l);
        exit(EXIT_FAILURE);
    }

    /* Open the session in promiscuous mode */
    pcap_handle = pcap_open_live(dev, BUFSIZ, 1, PCAP_PERIOD, errbuf);
    if (pcap_handle == NULL) {
        fprintf(stderr, "Couldn't open device %s: %s\n", dev, errbuf);
        libnet_destroy(l);
        return (2);
    }
    /* Compile and apply the filter */
    if (pcap_compile(pcap_handle, &fp, filter_exp, 0, net) == -1) {
        fprintf(stderr, "Couldn't parse filter %s: %s\n", filter_exp, pcap_geterr(pcap_handle));
        libnet_destroy(l);
        return (2);
    }
    if (pcap_setfilter(pcap_handle, &fp) == -1) {
        fprintf(stderr, "Couldn't install filter %s: %s\n", filter_exp, pcap_geterr(pcap_handle));
        libnet_destroy(l);
        return (2);
    }

    signal(SIGALRM, on_alarm);

    gettimeofday(&start_time, NULL);

    timer_create(CLOCK_MONOTONIC, NULL, &timer_id);
    timer_settime(timer_id, 0, &tspec, NULL);

    // don't know why, but pcap_dispatch does not return control to main after
    // timeout expires. so, we use nonblocking pcap on linux.
#ifdef __linux__
    pcap_setnonblock(pcap_handle, 1, errbuf);
#endif

    while( !do_stop ) {
        pcap_dispatch(pcap_handle, -1, got_packet, NULL);
#ifdef __linux__
        usleep(1000);
#endif
    }

    pcap_close(pcap_handle);

    i = tv_diff2msec(NULL);

    printf("found %d hosts in %d.%d seconds", nhosts, i/1000, i%1000);

    if( mac_to_find && !mac_found ) {
        printf(", but '%s' is not found.\n", mac_to_find);
    } else {
        puts("");
    }

    return (0);
}
开发者ID:tianzhishuizhu,项目名称:lltdscan,代码行数:101,代码来源:lltdscan.c


示例19: create_pcap_listener

/**
 *  Set up pcap listener for the given interfaces and protocols.
 *  @return a properly configured pcap_t* object for listening for the given protocols - NULL on error
 *  @see pcap_protocols
 */
pcap_t*
create_pcap_listener(const char * dev		///<[in] Device name to listen on
                     ,		     gboolean blocking		///<[in] TRUE if this is a blocking connection
                     ,		     unsigned listenmask	///<[in] Bit mask of protocols to listen for
                     ///< (see @ref pcap_protocols "list of valid bits")
                     ,		     struct bpf_program*prog)	///<[out] Compiled PCAP program
{
    pcap_t*			pcdescr = NULL;
    bpf_u_int32		maskp = 0;
    bpf_u_int32		netp = 0;
    char			errbuf[PCAP_ERRBUF_SIZE];
    char *			expr = NULL;
    int			filterlen = 1;
    unsigned		j;
    int			cnt=0;
    int			rc;
    const char ORWORD [] = " or ";
    gboolean		need_promisc = FALSE;

    BINDDEBUG(pcap_t);
//	setbuf(stdout, NULL);
    setvbuf(stdout, NULL, _IONBF, 0);
    errbuf[0] = '\0';

    // Search the list of valid bits so we can construct the libpcap filter
    // for the given set of protocols on the fly...
    // On this pass we just compute the amount of memory we'll need...
    for (j = 0, cnt = 0; j < DIMOF(filterinfo); ++j) {
        if (listenmask & filterinfo[j].filterbit) {
            ++cnt;
            if (cnt > 1) {
                filterlen += sizeof(ORWORD);
            }
            filterlen += strlen(filterinfo[j].filter);
        }
    }

    if (filterlen < 2) {
        g_warning("Constructed filter is too short - invalid mask argument.");
        return NULL;
    }
    if (NULL == (expr = malloc(filterlen))) {
        g_error("Out of memory!");
        return NULL;
    }
    // Same song, different verse...
    // This time around, we construct the filter
    expr[0] = '\0';
    for (j = 0, cnt = 0; j < DIMOF(filterinfo); ++j) {
        if (listenmask & filterinfo[j].filterbit) {
            ++cnt;
            if (cnt > 1) {
                g_strlcat(expr, ORWORD, filterlen);
            }
            g_strlcat(expr, filterinfo[j].filter, filterlen);
        }
    }
    if (pcap_lookupnet(dev, &netp, &maskp, errbuf) != 0) {
        // This is not a problem for non-IPv4 protocols...
        // It just looks up the ipv4 address - which we mostly don't care about.
        g_info("%s.%d: pcap_lookupnet(\"%s\") failed: [%s]"
               ,	__FUNCTION__, __LINE__, dev, errbuf);
    }

    if (NULL == (pcdescr = pcap_create(dev, errbuf))) {
        g_warning("pcap_create failed: [%s]", errbuf);
        goto oopsie;
    }
    //pcap_set_promisc(pcdescr, FALSE);
    for (j = 0; j < DIMOF(filterinfo); ++j) {
        if (listenmask & filterinfo[j].filterbit) {
            const char * addrstring = filterinfo[j].mcastaddr;
            if (addrstring && !_enable_mcast_address(addrstring, dev, TRUE)) {
                need_promisc = TRUE;
            }
        }
    }
    pcap_set_promisc(pcdescr, need_promisc);
#ifdef HAVE_PCAP_SET_RFMON
    pcap_set_rfmon(pcdescr, FALSE);
#endif
    pcap_setdirection(pcdescr, PCAP_D_IN);
    // Weird bug - returns -3 and doesn't show an error message...
    // And pcap_getnonblock also returns -3... Neither should happen AFAIK...
    errbuf[0] = '\0';
    if ((rc = pcap_setnonblock(pcdescr, !blocking, errbuf)) < 0 && errbuf[0] != '\0') {
        g_warning("pcap_setnonblock(%d) failed: [%s] [rc=%d]", !blocking, errbuf, rc);
        g_warning("Have no idea why this happens - current blocking state is: %d."
                  ,	pcap_getnonblock(pcdescr, errbuf));
    }
    pcap_set_snaplen(pcdescr, 1500);
    /// @todo deal with pcap_set_timeout() call here.
    if (blocking) {
        pcap_set_timeout(pcdescr, 240*1000);
    } else {
//.........这里部分代码省略.........
开发者ID:h4ck3rm1k3,项目名称:assimilation-official,代码行数:101,代码来源:pcap_min.c


示例20: probe_host

static void probe_host(const char *host)
{
	struct sockaddr_in sin;
	char pcap_errbuf[PCAP_ERRBUF_SIZE];
	struct pcap_pkthdr pkthdr;
	const uint8_t *data;
	struct bpf_program fp;
	pcap_t *ph;
	int fd;

	ph = pcap_create(iface, pcap_errbuf);
	if (ph == NULL) {
		perror("pcap_create");
		goto err1;
	}

	if (pcap_setnonblock(ph, 1, pcap_errbuf) == -1) {
		perror("pcap_setnonblock");
		goto err2;
	}

	if (pcap_setfilter(ph, &fp) == -1) {
		pcap_perror(ph, "pcap_setfilter");
		goto err2;
	}

	if (pcap_activate(ph) != 0) {
		pcap_perror(ph, "pcap_activate");
		goto err2;
	}

	if (pcap_compile(ph, &fp, "src host 127.0.0.1 and tcp and src port 80",
			 1, PCAP_NETMASK_UNKNOWN) == -1) {
		pcap_perror(ph, "pcap_compile");
		goto err2;
	}

	fd = socket(AF_INET, SOCK_STREAM, 0);
	if (fd < 0) {
		perror("socket");
		goto err3;
	}

	memset(&sin, 0, sizeof(sin));
	sin.sin_family		= AF_INET;
	sin.sin_port		= htons(port);
	sin.sin_addr.s_addr	= inet_addr(host);

	if (connect(fd, (struct sockaddr *)&sin, sizeof(sin)) < 0) {
		perror("connect");
		goto err4;
	}

	for (;;) {
		data = pcap_next(ph, &pkthdr);
		if (data == NULL)
			break;
		if (parse_packet(host, data))
			break;
	}

	close(fd);

err4:
	close(fd);
err3:
	pcap_freecode(&fp);
err2:
	pcap_close(ph);
err1:
	return;
}
开发者ID:AmVPN,项目名称:iptables,代码行数:72,代码来源:nfsynproxy.c



注:本文中的pcap_setnonblock函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
C++ pcap_snprintf函数代码示例发布时间:2022-05-30
下一篇:
C++ pcap_setfilter函数代码示例发布时间:2022-05-30
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap