Windows 7, msys2, compiler MinGW
Trying to connect to the MongoDB instance from the C++ code. Running mongod with the next command:
mongod --dbpath ./dev-db --bind_ip 127.0.0.1 --port 27017
I can normally connect to this database by mongo and in Robomongo.
For the c++ code, I successfully compiled and installed tha last stable Mongo C++ Driver. Code I take from the official tutorial:
#include <mongocxx/client.hpp>
#include <mongocxx/instance.hpp>
#include <mongocxx/uri.hpp>
mongocxx::uri uri("mongodb://127.0.0.1:27017");
mongocxx::client conn{uri};
auto db = conn["test"];
bsoncxx::document::value restaurant_doc =
document{} << "address" << open_document << "street"
<< "2 Avenue"
<< "zipcode"
<< "10075"
<< "building"
<< "1480"
<< "coord" << open_array << -73.9557413 << 40.7720266 << close_array
<< close_document << "borough"
<< "Manhattan"
<< "cuisine"
<< "Italian"
<< "grades" << open_array << open_document << "date"
<< bsoncxx::types::b_date{std::chrono::milliseconds{12323}} << "grade"
<< "A"
<< "score" << 11 << close_document << open_document << "date"
<< bsoncxx::types::b_date{std::chrono::milliseconds{121212}} << "grade"
<< "B"
<< "score" << 17 << close_document << close_array << "name"
<< "Vella"
<< "restaurant_id"
<< "41704620" << finalize;
auto res = db["restaurants"].insert_one(std::move(restaurant_doc))
And this provide the next error:
This application has requested the Runtime to terminate it in an unusual way.
Please contact the application's support team for more information.
terminate called after throwing an instance of 'mongocxx::v_noabi::bulk_write_exception'
what(): No suitable servers found (`serverSelectionTryOnce` set): [Failed to resolve '127.0.0.1']: generic server error
How can I avoid this issue and connect to the database?
Your copy is missing the first line of the example:
mongocxx::instance inst{};
See http://mongodb.github.io/mongo-cxx-driver/mongocxx-v3/tutorial/#make-a-connection. The mongocxx::instance constructor and destructor initialize and shut down the driver, respectively, so a mongocxx::instance must be created before using the driver and must remain alive for as long as the driver is in use.
It looks like it is attempting a DNS lookup of 127.0.0.1. Try changing it to be localhost instead (which will resolve to the same IP)
mongocxx::uri uri("mongodb://localhost:27017");
Related
I am developing a network scanner in C++ with the help of libtins library, I can be able to get MAC addresses and IP but I want to go further to know the vendor(eg: Intel Corporate) and Device Name (eg: DESKTOP-TO5P0BD) in C++
codes to get Mac and IP
// Retrieve the ARP layer info
const ARP& arp = pdu.rfind_pdu<ARP>();
std::cout << "Found :" << arp.sender_ip_addr() << ", " << arp.sender_hw_addr() << std::endl;
// Checking if it is an ARP reply?
if (arp.opcode() == ARP::REPLY) {
// Let's check if there's already an entry for this address
auto iter = addresses.find(arp.sender_ip_addr());
if (iter == addresses.end()) {
std::cout << "saving " << arp.sender_ip_addr() << ", " << arp.sender_hw_addr() << std::endl;
// We haven't seen this address. Save it.
addresses.insert({ arp.sender_ip_addr(), arp.sender_hw_addr() });
IPv4Address ip = arp.sender_ip_addr();
NetworkInterface iface(ip);
//std::cout << iface.name() << std::endl;
}
else {
std::cout << "already seen " << arp.sender_ip_addr() << ", " << arp.sender_hw_addr() << std::endl;
// We've seen this address. If it's not the same HW address, inform it
if (arp.sender_hw_addr() != iter->second) {
std::cout << "[WARNING] " << arp.sender_ip_addr() << " is at "
<< iter->second << " but also at " << arp.sender_hw_addr()
<< std::endl;
}
}
}
In order to get the vendor from the MAC address, you can have a look at this MAC OUI vendor database mantained by Wireshark. It's a text file with a simple format.
In order to get the "device name", you can do a NetBIOS name lookup. This StackOverflow question may help you.
If you'd like the Vendor Name from the MAC, you could get the MAC by reading arp -a (probably via the winapi). Next you need to search a vendor db, the wireshark list is good, there's also this one. As for the "Device Name", you could check this with WMI. Other than the more complex winapi for this, you could use a library like this one, which is much simpler. You'd need to make a request to the Win32_ComputerSystem class, which contains the Device Name and model number, among other things. MAC addresses can also be retrieved by WMI, instead make the query to Win32_NetworkAdapter - it gives all of the interfaces so be sure to find the right one!
I am working on a legacy C++ project which uses functions from blkid/blkid.h to access files on the local hard disk.
Since the project is quite big and hard to compile/run, I thought it would be a good idea to run it in a container. Creating the dockerfile to create the images went fine, the problems started when actually running the legacy project in a container.
I get errors when trying to access files on the disk using "blkid_devno_to_devname" to get the device id on which to write.
Here is a sample program that reproduces my problem
#include <iostream>
#include <sys/types.h>
#include <sys/stat.h>
#include <blkid/blkid.h>
int main() {
struct stat st;
std::string path = "my_file_path";
if (stat(path.data(), &st))
{
std::cout << "cannot get file statistics for file " << path << std::endl;
}
char *device_path = blkid_devno_to_devname(st.st_dev);
if(device_path == NULL)
{
std::cout << "cannot get device path for device ID " + std::to_string(st.st_dev) << std::endl;
}
}
On a regular file on my machine the device_path is not null, but running it on a docker always returns null.
What is not clear to me is how a docker container sees the disks it writes to.
To dig in, I looked into the different macros coming with stat (https://en.wikibooks.org/wiki/C_Programming/POSIX_Reference/sys/stat.h), I printed them on files on a container with different type of files (symlink, file, directory).
I modified the above little program to add this:
std::cout << "mode:" << st.st_mode << std::endl;
std::cout << "S_ISREG:" << S_ISREG(st.st_mode) << std::endl;
std::cout << "S_ISDIR:" << S_ISDIR(st.st_mode) << std::endl;
std::cout << "S_ISCHR:" << S_ISCHR(st.st_mode) << std::endl;
std::cout << "S_ISBLK:" << S_ISBLK(st.st_mode) << std::endl;
std::cout << "S_ISFIFO:" << S_ISFIFO(st.st_mode) << std::endl;
std::cout << "S_ISLNK:" << S_ISLNK(st.st_mode) << std::endl;
std::cout << "S_ISSOCK:" << S_ISSOCK(st.st_mode) << std::endl;
I thought there would be a difference depending on the type of layer the docker writes to, but I don't see any.
Be it on a volume, mount, or even on container layer (I mean on files neither on a volume nor mount).
On a mount, I would have expected the device id to be correct since as I understand it the mount is giving the container access to a physical drive (at least in my case - may not be true in general).
So why is blkid_devno_to_devname not returning anything on a docker container?
What am I not understanding properly?
P.S. for the record, blkid or /etc/fstab don't return anything on a container either.
Notes to the readers about my system:
working on a VM on windows (Oracle VM) with ubuntu 18 installed.
docker version: 19.03.6
Driver: overlay2
Im trying to get something done with C++ and MongoDB. So far there has been myriad of problems, but I have pulled through.
Then I got this one:
terminate called after throwing an instance of 'mongocxx::v_noabi::logic_error'
what(): invalid use of default constructed or moved-from mongocxx::client object
Aborted
And frankly, Im losing hope. This is the example Im trying to run:
https://docs.mongodb.com/getting-started/cpp/insert/.
Error appears when I try to run the compiled program. Im able to compile and run the 'hellomongo' example just fine, so at least partly, the driver is installed correctly.
My code:
#include <chrono>
#include <bsoncxx/builder/stream/document.hpp>
#include <bsoncxx/types.hpp>
#include <mongocxx/client.hpp>
#include <mongocxx/instance.hpp>
#include <mongocxx/uri.hpp>
using bsoncxx::builder::stream::document;
using bsoncxx::builder::stream::open_document;
using bsoncxx::builder::stream::close_document;
using bsoncxx::builder::stream::open_array;
using bsoncxx::builder::stream::close_array;
using bsoncxx::builder::stream::finalize;
int main(int, char**)
{
mongocxx::instance inst{};
mongocxx::client conn{};
auto db = conn["test"];
bsoncxx::document::value restaurant_doc =
document{} << "address" << open_document << "street"
<< "2 Avenue"
<< "zipcode"
<< "10075"
<< "building"
<< "1480"
<< "coord" << open_array << -73.9557413 << 40.7720266 << close_array
<< close_document << "borough"
<< "Manhattan"
<< "cuisine"
<< "Italian"
<< "grades" << open_array << open_document << "date"
<< bsoncxx::types::b_date { std::chrono::system_clock::time_point {
std::chrono::milliseconds { 12323 } } } << "grade"
<< "A"
<< "score" << 11 << close_document << open_document << "date"
<< bsoncxx::types::b_date { std::chrono::system_clock::time_point {
std::chrono::milliseconds { 12323 } } } << "grade"
<< "B"
<< "score" << 17 << close_document << close_array << "name"
<< "Vella"
<< "restaurant_id"
<< "41704620" << finalize;
// We choose to move in our document here, which transfers ownership to insert_one()
auto res = db["restaurants"].insert_one(std::move(restaurant_doc));
}
I use the following command to compile the example:
c++ --std=c++11 test.cpp -o test $(pkg-config --cflags --libs libmongocxx)
Any help is appreciated! I have very little experience with C++, so I'm bit lost to what could be the problem.
As acm pointed out, the docs on docs.mongodb.com are out of date. Github examples are working fine. I will mark this as answered.
Here is my code:
#include "MyClass.h"
#include <qstring.h>
#include <qdebug.h>
MyClass::MyClass()
{
QList<QextPortInfo> ports = QextSerialEnumerator::getPorts();
int counter=0;
while(counter<ports.size())
{
QString portName = ports[counter].portName;
QString productId= ports[counter].productID;
QString physicalName = ports[counter].physName;
QString vendorId = ports[counter].vendorID;
QString friendName = ports[counter].friendName;
string convertedPortName = portName.toLocal8Bit().constData();
string convertedProductId = productId.toLocal8Bit().constData();
string convertedPhysicalName = physicalName.toLocal8Bit().constData();
string convertedVendorId = vendorId.toLocal8Bit().constData();
string convertedFriendName = friendName.toLocal8Bit().constData();
cout << "Port Name: " << convertedPortName << endl;
cout << "Product ID:" << convertedProductId << endl;
cout << "Physical Name: " << convertedPhysicalName << endl;
cout << "Vendor Id: " << convertedVendorId << endl;
cout << "Friend Name: " << convertedFriendName << endl;
cout << endl;
counter++;
}
}
I have connected "Dreamcheeky Thunder Missile Launcher" USB toy, but I am unable to get it's Vendor ID or product ID or atleast anything related to it! See the following image
But using USBDView software, I can get all the details. See the following image
What is matter with My code? Or if it is simply not suitable?
Just running the installer for the toy and checking what it comes up with, it doesn't describe any API or documentation for accessing it as a serial port.
If you used some sort of monitoring program on their program you could maybe reverse engineer how it commands the device.
It may be easier just to interface with their UI directly. Using a program like AHK or calling SendInput() to coordinates relative to the upper left corner of their UI, you could command the directions of the device.
EDIT: More links related to this:
Because the USB device doesn't get listed as a COM# (how serial port shows up), and it is a HID device, you need a library that can talk to that. Here are some links that should help you get there:
http://www.qtcentre.org/threads/41075-USB-HID-connect-on-QT
http://www.signal11.us/oss/hidapi/
https://github.com/iia/Qt_libusb
It also looks like the guys at Robo Realm have done it already:
http://www.roborealm.com/help/DC_Missile.php
http://www.roborealm.com/help/USB_HID.php
http://www.roborealm.com/tutorial/usb_missile_launcher/slide010.php
Hope that helps.
I'm trying to display a small MySQL table via C++ using the MySQL/C++ Connector, but when I execute the following function, my program either quits with the message "Aborted" or I get a segfault. Can anyone tell me what I'm doing wrong here? I thought I followed the documentation pretty well. :/
void
addressBook::display(sql::Connection* con)
{
sql::Statement *stmt;
sql::ResultSet *res;
// Create the statement object
stmt = con->createStatement();
// Execute a query and store the result in res
res = stmt->executeQuery("SELECT * FROM address_book "
"ORDER BY last_name, first_name");
// Loop through the results and display them
if(res)
{
while(res->next())
{
std::cout << "Name: " << res->getString("first_name")
<< " " << res->getString("last_name") << std::endl
<< "Phone: " << res->getString("phone") << std::endl
<< "eMail: " << res->getString("email") << std::endl
<< "City: " << res->getString("city") << std::endl
<< "Comments: " << res->getString("comments")
<< std::endl << std::endl;
}
}
delete stmt;
delete res;
}
The full (as of yet, unfinished) program may be found here, for reference. http://pastebin.com/kWnknHi4
Also, each field in the table being called contains a valid string.
Edit The debugger message can be found here: http://pastebin.com/NnSqV8hv
It looks like you're calling delete in the wrong order. The example deletes res first.
The ResultSet destructor may reference the associated Statement.
Generally, you should do free/delete in the opposite order you created/allocated the object.
The problem was that the libraries were installed incorrectly on my system; according to the docs, you run make clean as an intermediary step, when it should just be make.
Thanks to vinleod from ##c++-basic (Vincent Damewood of http://damewood.us/) for the help in figuring that out.