示例#1
0
CpiDeviceListUpnp::CpiDeviceListUpnp(FunctorCpiDevice aAdded, FunctorCpiDevice aRemoved)
    : CpiDeviceList(aAdded, aRemoved)
    , iStarted(false)
    , iXmlFetchSem("DRLS", 0)
    , iXmlFetchLock("DRLM")
{
    NetworkInterfaceList& ifList = Stack::NetworkInterfaceList();
    NetworkInterface* current = ifList.CurrentInterface();
    iRefreshTimer = new Timer(MakeFunctor(*this, &CpiDeviceListUpnp::RefreshTimerComplete));
    iInterfaceChangeListenerId = ifList.AddCurrentChangeListener(MakeFunctor(*this, &CpiDeviceListUpnp::CurrentNetworkInterfaceChanged));
    iSubnetChangeListenerId = ifList.AddSubnetChangeListener(MakeFunctor(*this, &CpiDeviceListUpnp::SubnetChanged));
    if (current == NULL) {
        iInterface = 0;
        iUnicastListener = NULL;
        iMulticastListener = NULL;
        iNotifyHandlerId = 0;
    }
    else {
        iInterface = current->Address();
        iUnicastListener = new SsdpListenerUnicast(*this, iInterface);
        iMulticastListener = &Stack::MulticastListenerClaim(iInterface);
        iNotifyHandlerId = iMulticastListener->AddNotifyHandler(this);
        delete current;
    }
}
/*!
	Scans an interface and enumerates all baos devices.
	It sends a search request as outlined in the BAOS 1.2 protocol
	documentation and waits for the responses. There are lots of
	magic numbers here and hard-coded offsets... See the spec
	for more information on what is happening here...

	We implement a receive timeout, and keep receiving until this
	timeout elapses. If this timeout is too fast, increase it to 500
	or 1000 for example.
*/
void BaosIpEnumerator::scanInterface(const NetworkInterface& networkInterface)
{
	poco_information(LOGGER(),
	                 format("Search devices on interface: %s (%s)",
	                        networkInterface.displayName(),
	                        networkInterface.address().toString()));

	try
	{
		// initialize socket
		MulticastSocket socket;
		socket.bind(SocketAddress(networkInterface.address(), 0));
		socket.setTimeToLive(DefaultMulticastTTL);

		// builds and sends a SEARCH_REQUEST to the socket
		sendSearchRequestFrame(socket);

		// wait for SEARCH_RESPONSES and collect it
		waitForSearchResponseFrames(socket);
	}
	catch (Poco::Exception& e)
	{
		poco_warning(LOGGER(), format("... search failed with error: %s", e.displayText()));
	}
}
示例#3
0
void CpiDeviceListUpnp::HandleInterfaceChange(TBool aNewSubnet)
{
    NetworkInterface* current = Stack::NetworkInterfaceList().CurrentInterface();
    iLock.Wait();
    delete iUnicastListener;
    iUnicastListener = NULL;
    if (iMulticastListener != NULL) {
        iMulticastListener->RemoveNotifyHandler(iNotifyHandlerId);
        iNotifyHandlerId = 0;
        Stack::MulticastListenerRelease(iInterface);
        iMulticastListener = NULL;
    }

    if (current == NULL) {
        iInterface = 0;
        RemoveAll();
        iLock.Signal();
        return;
    }

    iInterface = current->Address();
    delete current;
    if (aNewSubnet) {
        RemoveAll();
    }
    iUnicastListener = new SsdpListenerUnicast(*this, iInterface);
    iUnicastListener->Start();
    iMulticastListener = &Stack::MulticastListenerClaim(iInterface);
    iNotifyHandlerId = iMulticastListener->AddNotifyHandler(this);
    iLock.Signal();
    Refresh();
}
示例#4
0
文件: main.cpp 项目: Archcady/mbed-os
void test_bring_up_down() {
    NetworkInterface* net = MBED_CONF_APP_OBJECT_CONSTRUCTION;

    for (int i = 0; i < COUNT; i++) {
        int err = MBED_CONF_APP_CONNECT_STATEMENT;
        TEST_ASSERT_EQUAL(0, err);

        printf("MBED: IP Address %s\r\n", net->get_ip_address());
        TEST_ASSERT(net->get_ip_address());

        UDPSocket udp;
        err = udp.open(net);
        TEST_ASSERT_EQUAL(0, err);
        err = udp.close();
        TEST_ASSERT_EQUAL(0, err);

        TCPSocket tcp;
        err = tcp.open(net);
        TEST_ASSERT_EQUAL(0, err);
        err = tcp.close();
        TEST_ASSERT_EQUAL(0, err);

        err = net->disconnect();
        TEST_ASSERT_EQUAL(0, err);
    }
}
示例#5
0
void PacketSender::open_l2_socket(const NetworkInterface& iface) {
    #if defined(BSD) || defined(__FreeBSD_kernel__)
        int sock = -1;
        // At some point, there should be an available device
        for (int i = 0; sock == -1;i++) {
            std::ostringstream oss;
            oss << "/dev/bpf" << i;

            sock = open(oss.str().c_str(), O_RDWR);
        }
        if(sock == -1) 
            throw socket_open_error(make_error_string());
        
        struct ifreq ifr;
        strncpy(ifr.ifr_name, iface.name().c_str(), sizeof(ifr.ifr_name) - 1);
        if(ioctl(sock, BIOCSETIF, (caddr_t)&ifr) < 0) {
            ::close(sock);
            throw socket_open_error(make_error_string());
        }
        _ether_socket[iface.id()] = sock;
    #else
    if (_ether_socket == INVALID_RAW_SOCKET) {
        _ether_socket = socket(PF_PACKET, SOCK_RAW, htons(ETH_P_ALL));
        
        if (_ether_socket == -1)
            throw socket_open_error(make_error_string());
    }
    #endif
}
示例#6
0
文件: main.cpp 项目: 0xc0170/mbed
static void _ifup()
{
    NetworkInterface *net = NetworkInterface::get_default_instance();
    nsapi_error_t err = net->connect();
    TEST_ASSERT_EQUAL(NSAPI_ERROR_OK, err);
    printf("MBED: TLSClient IP address is '%s'\n", net->get_ip_address());
}
示例#7
0
void RedirectorSrv::server_sockevent( nlink_server *cptr, uint16 revents, void *myNet ) {
	NetworkInterface * client;
	struct nlink_client *ncptr;
	if(revents & PF_READ)
	{
		client = ( ( NetworkInterface * ) myNet )->getConnection( );
		if (!client) 
			return;
		uint32 nonblockingstate = true;
		IOCTL_SOCKET( client->getSocketID(), IOCTL_NOBLOCK, &nonblockingstate );

		ncptr = new nlink_client;
		if(ncptr == NULL)
			return;
		memset(ncptr, 0, sizeof(*ncptr));
		ncptr->hdr.type = RCLIENT;
		ncptr->hdr.fd = client->getSocketID();
		
		nlink_insert((struct nlink *)ncptr);

		Client *pClient = new Client();
		pClient->BindNI(client);
		ncptr->pClient = pClient;
		pClient->getNetwork()->sendData( mDestination.length( ), mDestination.c_str( ) );
		Log::getSingleton( ).outString( "REDIRECTOR: Sent world server" );
		disconnect_client( ncptr );
	}
}
示例#8
0
int HistoricalInterface::loadData() {
  time_t actual_epoch, adjust_to_epoch;
  int ret_state = CONST_HISTORICAL_OK;
  NetworkInterface * iface = ntop->getInterfaceById(interface_id);

  if((iface != NULL) && (from_epoch != 0) && (to_epoch != 0)) {
    u_int8_t iface_dump_id;

    iface_dump_id = iface->get_id();
    actual_epoch = from_epoch;
    adjust_to_epoch = to_epoch - 300; // Adjust to epoch each file contains 5 minute of data
    while (actual_epoch <= adjust_to_epoch && isRunning()) {
      char path[MAX_PATH];
      char db_path[MAX_PATH];
  
      memset(path, 0, sizeof(path));
      memset(db_path, 0, sizeof(db_path));

      strftime(path, sizeof(path), "%Y/%m/%d/%H/%M", localtime(&actual_epoch));
      snprintf(db_path, sizeof(db_path), "%s/%u/flows/%s.sqlite",
                    ntop->get_working_dir(), iface_dump_id , path);

     loadData(db_path);

      num_historicals++;
      actual_epoch += 300; // 5 minute steps
    }
  }

  on_load = false;

  return ret_state;
}
void NetworkInterfaceTest::testForAddress()
{
	NetworkInterface::Map map = NetworkInterface::map();
	for (NetworkInterface::Map::const_iterator it = map.begin(); it != map.end(); ++it)
	{
		// not all interfaces have IP configured
		if (it->second.addressList().empty()) continue;

		if (it->second.supportsIPv4())
		{
			NetworkInterface ifc = NetworkInterface::forAddress(it->second.firstAddress(IPAddress::IPv4));
			assert (ifc.firstAddress(IPAddress::IPv4) == it->second.firstAddress(IPAddress::IPv4));

			IPAddress addr(IPAddress::IPv4);
			assert (addr.isWildcard());
			it->second.firstAddress(addr, IPAddress::IPv4);
			assert (!addr.isWildcard());
		}
		else
		{
			try
			{
				it->second.firstAddress(IPAddress::IPv4);
				fail ("must throw");
			}
			catch (NotFoundException&) { }

			IPAddress addr(IPAddress::IPv4);
			assert (addr.isWildcard());
			it->second.firstAddress(addr, IPAddress::IPv4);
			assert (addr.isWildcard());
		}
	}
}
示例#10
0
void NetworkInterface::onPacketReceivedCb(u_char *user,
                                          const struct pcap_pkthdr *h,
                                          const u_char *bytes)
{
  NetworkInterface *host = reinterpret_cast<NetworkInterface*>(user);
  host->onPacketReceived(h, bytes);
}
示例#11
0
int main(int argc, const char *argv[])
{
	NetworkInterface ni;
	ni.hostGame();

	ni.endGame();
	return 0;
}
示例#12
0
void NetworkInterfaceTest::testForIndex()
{
	NetworkInterface::Map map = NetworkInterface::map();
	for (NetworkInterface::Map::const_iterator it = map.begin(); it != map.end(); ++it)
	{
		NetworkInterface ifc = NetworkInterface::forIndex(it->second.index());
		assert (ifc.index() == it->second.index());
	}
}
示例#13
0
static void RandomiseUdn(Bwh& aUdn)
{
    aUdn.Grow(aUdn.Bytes() + 1 + Ascii::kMaxUintStringBytes + 1);
    aUdn.Append('-');
    Bws<Ascii::kMaxUintStringBytes> buf;
    NetworkInterface* nif = Stack::NetworkInterfaceList().CurrentInterface();
    TUint max = nif->Address();
    delete nif;
    (void)Ascii::AppendDec(buf, Random(max));
    aUdn.Append(buf);
    aUdn.PtrZ();
}
示例#14
0
void MulticastSocket::setInterface(const NetworkInterface& interface)
{
	if (!interface.supportsIPv6())
	{
		impl()->setOption(IPPROTO_IP, IP_MULTICAST_IF, interface.address());
	}
	else
	{
#if defined(POCO_HAVE_IPv6)
		impl()->setOption(IPPROTO_IPV6, IPV6_MULTICAST_IF, interface.index());
#endif
	}
}
void MULTIHOMING_ASYNCHRONOUS_DNS()
{
    rtos::Semaphore semaphore;
    dns_application_data data;
    data.semaphore = &semaphore;



    for (unsigned int i = 0; i < MBED_CONF_APP_DNS_TEST_HOSTS_NUM; i++) {

        for (unsigned int interface_index = 0; interface_index < MBED_CONF_MULTIHOMING_MAX_INTERFACES_NUM; interface_index++) {
            NetworkInterface  *interface = get_interface(interface_index);
            if (interface == NULL) {
                continue;
            }

            for (unsigned int j = 0; j < interface_num; j++) {

                nsapi_error_t err = interface->gethostbyname_async(dns_test_hosts[i],
                                                                       mbed::Callback<void(nsapi_error_t, SocketAddress *)>(hostbyname_cb, (void *) &data), NSAPI_UNSPEC, interface_name[j]);
                TEST_ASSERT(err >= 0);

                semaphore.wait();

                TEST_ASSERT_EQUAL(NSAPI_ERROR_OK, data.result);
                printf("DNS: query  interface_name %s %d \n", interface_name[j], j);
                if (data.result == NSAPI_ERROR_OK) {
                    result_ok++;
                    printf("DNS: query OK \"%s\" => \"%s\"\n", dns_test_hosts[i], data.addr.get_ip_address());
                } else if (data.result == NSAPI_ERROR_DNS_FAILURE) {
                    result_dns_failure++;
                    printf("DNS: query \"%s\" => DNS failure\n", dns_test_hosts[i]);
                } else if (data.result == NSAPI_ERROR_TIMEOUT) {
                    result_exp_timeout++;
                    printf("DNS: query \"%s\" => timeout\n", dns_test_hosts[i]);
                } else if (data.result == NSAPI_ERROR_NO_MEMORY) {
                    result_no_mem++;
                    printf("DNS: query \"%s\" => no memory\n", dns_test_hosts[i]);
                } else {
                    printf("DNS: query \"%s\" => %d, unexpected answer\n", dns_test_hosts[i], data.result);
                    TEST_ASSERT(data.result == NSAPI_ERROR_OK || data.result == NSAPI_ERROR_NO_MEMORY || data.result == NSAPI_ERROR_DNS_FAILURE || data.result == NSAPI_ERROR_TIMEOUT);
                }

            }
        }



    }
}
示例#16
0
void MulticastSocket::setInterface(const NetworkInterface& interfc)
{
	if (address().family() == IPAddress::IPv4)
	{
		impl()->setOption(IPPROTO_IP, IP_MULTICAST_IF, interfc.firstAddress(IPAddress::IPv4));
	}
#if defined(POCO_HAVE_IPv6)
	else if (address().family() == IPAddress::IPv6)
	{
		impl()->setOption(IPPROTO_IPV6, IPV6_MULTICAST_IF, interfc.index());
	}
#endif
	else
		throw UnsupportedFamilyException("Unknown or unsupported socket family.");
}
示例#17
0
// Send syns to the given ip address, using the destination ports provided.
void send_syns(const NetworkInterface &iface, IPv4Address dest_ip, const vector<string> &ips) {
    // Retrieve the addresses.
    NetworkInterface::Info info = iface.addresses();
    PacketSender sender;
    // Allocate the IP PDU
    IP ip = IP(dest_ip, info.ip_addr) / TCP();
    // Get the reference to the TCP PDU
    TCP &tcp = ip.rfind_pdu<TCP>();
    // Set the SYN flag on.
    tcp.set_flag(TCP::SYN, 1);
    // Just some random port. 
    tcp.sport(1337);
    cout << "Sending SYNs..." << endl;
    for(vector<string>::const_iterator it = ips.begin(); it != ips.end(); ++it) {
        // Set the new port and send the packet!
        tcp.dport(atoi(it->c_str()));
        sender.send(ip);
    }
    // Wait 1 second.
    sleep(1);
    /* Special packet to indicate that we're done. This will be sniffed
     * by our function, which will in turn return false.  
     */
    tcp.set_flag(TCP::RST, 1);
    // Pretend we're the scanned host...
    ip.src_addr(dest_ip);
    // We use an ethernet pdu, otherwise the kernel will drop it.
    EthernetII eth = EthernetII(info.hw_addr, info.hw_addr) / ip;
    sender.send(eth, iface);
}
示例#18
0
void receive_probe_requests(NetworkInterface iface) {
	SnifferConfiguration config;
	config.set_rfmon(true);
	config.set_filter("type mgt subtype probe-req || type data subtype null");
	Sniffer sniffer(iface.name(), config);
	while(true) process(sniffer.next_packet());
}
NetworkInterfaceBytes EmittedReceivedBytes::getEmittedReceivedNumberOfBytesNow(
		pid_t pid, const NetworkInterface &networkInterface) {
	NetworkInterfaceBytes result(networkInterface.getName());
	QFile statFile(statFileName.arg(pid));
	if (!statFile.open(QIODevice::ReadOnly | QIODevice::Text)) {
		logger.log(Logger::LOG_ERROR, "unable to read stat file");
		return result;
	}

	QTextStream statFileStream(&statFile);

	// Skip the first line
	statFileStream.readLine();

	// TODO get the real received/transmit bytes according to the specified network interface
	// (cause now, we cannot know what interface is used)
	QStringList values(
			statFileStream.readLine().split(QRegExp("\\s+"),
					QString::SkipEmptyParts));

	long emittedBytes = values[5].toLong() + values[9].toLong()
			+ values[12].toLong();
	result.setEmittedBytes(emittedBytes);

	long receivedBytes = values[7].toLong() + values[11].toLong()
			+ values[13].toLong();
	result.setReceivedBytes(receivedBytes);

	return result;
}
示例#20
0
bool PacketSender::ether_socket_initialized(const NetworkInterface& iface) const {
    #if defined(BSD) || defined(__FreeBSD_kernel__)
    return _ether_socket.count(iface.id());
    #else
    return _ether_socket != INVALID_RAW_SOCKET;
    #endif
}
示例#21
0
void RadioTap::send(PacketSender &sender, const NetworkInterface &iface) {
    if(!iface)
        throw invalid_interface();

#if !defined(BSD) && !defined(__FreeBSD_kernel__)
    struct sockaddr_ll addr;

    memset(&addr, 0, sizeof(struct sockaddr_ll));

    addr.sll_family = Endian::host_to_be<uint16_t>(PF_PACKET);
    addr.sll_protocol = Endian::host_to_be<uint16_t>(ETH_P_ALL);
    addr.sll_halen = 6;
    addr.sll_ifindex = iface.id();

    const Tins::Dot11 *wlan = tins_cast<Tins::Dot11*>(inner_pdu());
    if(wlan) {
        Tins::Dot11::address_type dot11_addr(wlan->addr1());
        std::copy(dot11_addr.begin(), dot11_addr.end(), addr.sll_addr);
    }

    sender.send_l2(*this, (struct sockaddr*)&addr, (uint32_t)sizeof(addr));
#else
    sender.send_l2(*this, 0, 0, iface);
#endif
}
示例#22
0
文件: Lua.cpp 项目: ctcble/ntopng
static int ntop_set_active_interface_id(lua_State* vm) {
  NetworkInterface *iface;
  u_int32_t id;

  if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TNUMBER)) return(CONST_LUA_ERROR);
  id = (u_int32_t)lua_tonumber(vm, 1);

  iface = ntop->getInterfaceId(id);

  if(iface != NULL)
    lua_pushstring(vm, iface->get_name());
  else
    lua_pushnil(vm);  
  
  return(CONST_LUA_OK);
}
示例#23
0
void PacketSender::close_socket(SocketType type, const NetworkInterface &iface) {
    if(type == ETHER_SOCKET) {
        #if defined(BSD) || defined(__FreeBSD_kernel__)
        BSDEtherSockets::iterator it = _ether_socket.find(iface.id());
        if(it == _ether_socket.end())
            throw invalid_socket_type();
        if(::close(it->second) == -1)
            throw socket_close_error(make_error_string());
        _ether_socket.erase(it);
        #elif !defined(WIN32)
        if(_ether_socket == INVALID_RAW_SOCKET)
            throw invalid_socket_type();
        if(::close(_ether_socket) == -1)
            throw socket_close_error(make_error_string());
        _ether_socket = INVALID_RAW_SOCKET;
        #endif
    }
    else {
        if(type >= SOCKETS_END || _sockets[type] == INVALID_RAW_SOCKET)
            throw invalid_socket_type();
        #ifndef WIN32
        if(close(_sockets[type]) == -1)
            throw socket_close_error(make_error_string());
        #else
        closesocket(_sockets[type]);
        #endif
        _sockets[type] = INVALID_RAW_SOCKET;
    }
}
示例#24
0
const std::string RmmKeyGenerator::generate_key(const NetworkInterface& interface) {
    const auto mac_address = interface.get_mac_address();

    if (!mac_address.has_value()) {
        throw KeyValueMissingError("MAC address is missing.");
    }

    return generate_key_base(interface) + mac_address.value();
}
示例#25
0
int PacketSender::get_ether_socket(const NetworkInterface& iface) {
    if(!ether_socket_initialized(iface))
        open_l2_socket(iface);
    #if defined(BSD) || defined(__FreeBSD_kernel__)
    return _ether_socket[iface.id()];
    #else
    return _ether_socket;
    #endif
}
示例#26
0
NetworkState::NetworkState(String interfaceName):
    interfaceName_(interfaceName),
    networkMask_(0)
{
    Ref<RouteInfoList> routingTable = RouteInfo::queryTable();
    for (int i = 0; i < routingTable->count(); ++i) {
        RouteInfo *entry = routingTable->at(i);
        if (entry->source() || entry->destination()) continue;
        if (interfaceName_ != "" && entry->outputInterface() != interfaceName_) continue;
        interfaceName_ = entry->outputInterface();
        gateway_ = entry->gateway();
        break;
    }

    Ref<NetworkInterfaceList> interfaceList = NetworkInterface::queryAll(AF_UNSPEC);
    for (int i = 0; i < interfaceList->count(); ++i) {
        NetworkInterface *candidate = interfaceList->at(i);
        if (candidate->name() == interfaceName_) {
            interface_ = candidate;
            Ref<SocketAddressList> addressList = interface_->addressList();
            if (!gateway_) {
                for (int j = 0; j < addressList->count(); ++j) {
                    SocketAddress *address = addressList->at(j);
                    if (address->family() != AF_INET) continue;
                    address_ = address;
                    break;
                }
            }
            if (!address_) {
                for (int j = 0; j < addressList->count(); ++j) {
                    SocketAddress *address = addressList->at(j);
                    if (gateway_ && address->family() != gateway_->family()) continue;
                    address_ = address;
                    break;
                }
            }
        }
    }

    Ref<SocketAddressEntry> entry = cast<SocketAddressEntry>(address_);
    if (entry)
        networkMask_ = entry->networkMask();
}
示例#27
0
const std::string RmmKeyGenerator::generate_key(const Fan& fan, const NetworkInterface& zone_network_interface) {
    const auto zone_nic_mac = zone_network_interface.get_mac_address();
    const auto slot_id = fan.get_slot_id();

    if (!zone_nic_mac.has_value()) {
        throw KeyValueMissingError("Zone NIC MAC address is missing.");
    }

    return generate_key_base(fan) + zone_nic_mac.value() + std::to_string(static_cast<unsigned int>(slot_id));
}
示例#28
0
void MulticastSocket::leaveGroup(const IPAddress& groupAddress, const NetworkInterface& interfc)
{
	if (groupAddress.af() == AF_INET)
	{
		struct ip_mreq mr;
		std::memcpy(&mr.imr_multiaddr, groupAddress.addr(), groupAddress.length());
		std::memcpy(&mr.imr_interface, interfc.firstAddress(IPAddress::IPv4).addr(), interfc.firstAddress(IPAddress::IPv4).length());
		impl()->setRawOption(IPPROTO_IP, IP_DROP_MEMBERSHIP, &mr, sizeof(mr));
	}
	else
	{
#if defined(POCO_HAVE_IPv6)
		struct ipv6_mreq mr;
		std::memcpy(&mr.ipv6mr_multiaddr, groupAddress.addr(), groupAddress.length());
		mr.ipv6mr_interface = interfc.index();
		impl()->setRawOption(IPPROTO_IPV6, IPV6_DROP_MEMBERSHIP, &mr, sizeof(mr));
#endif
	}
}
示例#29
0
const std::string
RmmKeyGenerator::generate_key(const ThermalZone& thermal_zone, const NetworkInterface& zone_network_interface) {
    const auto zone_nic_mac = zone_network_interface.get_mac_address();

    if (!zone_nic_mac.has_value()) {
        throw KeyValueMissingError("Zone NIC MAC address is missing.");
    }

    return generate_key_base(thermal_zone) + zone_nic_mac.value();
}
示例#30
0
const std::string
RmmKeyGenerator::generate_key(const EthernetSwitchPortVlan& vlan, const NetworkInterface& network_interface) {
    const auto vlan_id = vlan.get_vlan_id();
    const auto nic_mac = network_interface.get_mac_address();

    if ((!vlan_id.has_value()) || (!nic_mac.has_value())) {
        throw KeyValueMissingError("Unique propery not found.");
    }

    return generate_key_base(vlan) + std::to_string(vlan_id.value()) + nic_mac.value();
}