C++ ping-like function without superuser access - c++

I am trying to write a simple C++ ping function to see if a network address is responding. I don't need ICMP specifically, I just need to see if the server is there and responding to anything. I have been doing some research and every solution I come up with requires creating a raw socket or something which requires the program to have sudo access. I won't be able to guarantee that the system I am running this on will be able to modify the network stack, so this is not valid.
Here are some related questions I have already looked at.
Opening RAW sockets in linux without being superuser
ICMP sockets (linux)
How to Ping Using Sockets Library - C
Why does ping work without administrator privileges?
C++ Boost.asio Ping
It appears that ping requires superuser access for a good reason. I don't want to purposefully create a security loophole, I just want to see if a server is responding. Is there a good c++ function or resource that can do this? I will make sure to post any sample solution I come up with. I need a Linux (BSD) socket solution. Since almost every unix-like system runs SSH, I can even just test against port 22. I am only going to target Linux systems as a constraint.
Thanks

Here is an example with popen. I would love a better solution, so if there is a socket or other method which does not resort to a shell call, I would greatly appreciate it. This should run with just g++ ping_demo.cpp -o ping_demo. Let me know if it causes compile errors.
// C++ Libraries
#include <cstdio>
#include <iostream>
#include <sstream>
#include <string>
/**
* #brief Convert String to Number
*/
template <typename TP>
TP str2num( std::string const& value ){
std::stringstream sin;
sin << value;
TP output;
sin >> output;
return output;
}
/**
* #brief Convert number to string
*/
template <typename TP>
std::string num2str( TP const& value ){
std::stringstream sin;
sin << value;
return sin.str();
}
/**
* #brief Execute Generic Shell Command
*
* #param[in] command Command to execute.
* #param[out] output Shell output.
* #param[in] mode read/write access
*
* #return 0 for success, 1 otherwise.
*
*/
int Execute_Command( const std::string& command,
std::string& output,
const std::string& mode = "r")
{
// Create the stringstream
std::stringstream sout;
// Run Popen
FILE *in;
char buff[512];
// Test output
if(!(in = popen(command.c_str(), mode.c_str()))){
return 1;
}
// Parse output
while(fgets(buff, sizeof(buff), in)!=NULL){
sout << buff;
}
// Close
int exit_code = pclose(in);
// set output
output = sout.str();
// Return exit code
return exit_code;
}
/**
* #brief Ping
*
* #param[in] address Address to ping.
* #param[in] max_attempts Number of attempts to try and ping.
* #param[out] details Details of failure if one occurs.
*
* #return True if responsive, false otherwise.
*
* #note { I am redirecting stderr to stdout. I would recommend
* capturing this information separately.}
*/
bool Ping( const std::string& address,
const int& max_attempts,
std::string& details )
{
// Format a command string
std::string command = "ping -c " + num2str(max_attempts) + " " + address + " 2>&1";
std::string output;
// Execute the ping command
int code = Execute_Command( command, details );
return (code == 0);
}
/**
* #brief Main Function
*/
int main( int argc, char* argv[] )
{
// Parse input
if( argc < 2 ){
std::cerr << "usage: " << argv[0] << " <address> <max-attempts = 3>" << std::endl;
return 1;
}
// Get the address
std::string host = argv[1];
// Get the max attempts
int max_attempts = 1;
if( argc > 2 ){
max_attempts = str2num<int>(argv[2]);
}
if( max_attempts < 1 ){
std::cerr << "max-attempts must be > 0" << std::endl;
return 1;
}
// Execute the command
std::string details;
bool result = Ping( host, max_attempts, details );
// Print the result
std::cout << host << " ";
if( result == true ){
std::cout << " is responding." << std::endl;
}
else{
std::cout << " is not responding. Cause: " << details << std::endl;
}
return 0;
}
Sample outputs
$> g++ ping_demo.cpp -o ping_demo
$> # Valid Example
$> ./ping_demo localhost
localhost is responding.
$> # Invalid Example
$> ./ping_demo localhostt
localhostt is not responding. Cause: ping: unknown host localhostt
$> # Valid Example
$> ./ping_demo 8.8.8.8
8.8.8.8 is responding.

I created an easy to use ping class with added ethernet port detection capability. I based the code on msmith81886's answer but wanted to condense for those using it in industry.
ping.hpp
#ifndef __PING_HPP_
#define __PING_HPP_
#include <cstdio>
#include <iostream>
#include <sstream>
#include <string>
#include <fstream>
#include <cerrno>
#include <cstring>
class system_ping
{
public:
int test_connection (std::string ip_address, int max_attempts, bool check_eth_port = false, int eth_port_number = 0);
private:
int ping_ip_address(std::string ip_address, int max_attempts, std::string& details);
};
#endif
ping.cpp
#include "../include/ping.hpp"
int system_ping::ping_ip_address(std::string ip_address, int max_attempts, std::string& details)
{
std::stringstream ss;
std::string command;
FILE *in;
char buff[512];
int exit_code;
try
{
command = "ping -c " + std::to_string(max_attempts) + " " + ip_address + " 2>&1";
if(!(in = popen(command.c_str(), "r"))) // open process as read only
{
std::cerr << __FILE__ << "(" << __FUNCTION__ << ":" << __LINE__ << ") | popen error = " << std::strerror(errno) << std::endl;
return -1;
}
while(fgets(buff, sizeof(buff), in) != NULL) // put response into stream
{
ss << buff;
}
exit_code = pclose(in); // blocks until process is done; returns exit status of command
details = ss.str();
}
catch (const std::exception &e)
{
std::cerr << __FILE__ << "(" << __FUNCTION__ << ":" << __LINE__ << ") | e.what() = " << e.what() << std::endl;
return -2;
}
return (exit_code == 0);
}
int system_ping::test_connection (std::string ip_address, int max_attempts, bool check_eth_port, int eth_port_number)
{
std::cout << __FILE__ << "(" << __FUNCTION__ << ":" << __LINE__ << ") | started" << std::endl;
int eth_conn_status_int;
std::string details;
try
{
if (check_eth_port)
{
std::ifstream eth_conn_status ("/sys/class/net/eth" + std::to_string(eth_port_number) + "/carrier");
eth_conn_status >> eth_conn_status_int; // 0: not connected; 1: connected
if (eth_conn_status_int != 1)
{
std::cerr << __FILE__ << "(" << __FUNCTION__ << ":" << __LINE__ << ") | eth" << std::to_string(eth_port_number) << " unplugged";
return -1;
}
}
if (ping_ip_address(ip_address, max_attempts, details) != 1)
{
std::cerr << __FILE__ << "(" << __FUNCTION__ << ":" << __LINE__ << ") | cannot ping " << ip_address << " | " << details << std::endl;
return -2;
}
}
catch (const std::exception &e)
{
std::cerr << __FILE__ << "(" << __FUNCTION__ << ":" << __LINE__ << ") | e.what() = " << e.what() << std::endl;
return -3;
}
std::cout << __FILE__ << "(" << __FUNCTION__ << ":" << __LINE__ << ") | ping " << ip_address << " OK" << std::endl;
std::cout << __FILE__ << "(" << __FUNCTION__ << ":" << __LINE__ << ") | ended" << std::endl;
return 0;
}

Related

Double free or corruption C++ Avro

I need to serialize a JSON string using Avro in C++.
I installed the libserdes library (https://github.com/confluentinc/libserdes) and I used the example code
./examples/kafka-serdes-avro-console-producer.cpp
to write a main,
which serializes a JSON string as follows.
{"s":"BTCUSDT","c":"spread","u":123456789,"a":20000.4,"b":21000.5,"A":1.25,"B":0.58,"p":-1,"P":-1,"st":-1,"rt":1675000000123000}
Here is the code
#include "fh_price_t.h"
#include "avro/Encoder.hh"
#include "avro/Decoder.hh"
#include <avro/Generic.hh>
#include <avro/Specific.hh>
#include <avro/Exception.hh>
#include "libserdes/serdescpp-avro.h"
#include <iostream>
#include <sstream>
#include <string>
#include <fstream>
#define FATAL(reason...) do { \
std::cerr << "% FATAL: " << reason << std::endl; \
exit(1); \
} while (0)
template<class T> std::string to_string_a (const T& x) {
std::ostringstream oss;
oss << x;
return oss.str();
}
/**
* Convert JSON to Avro Datum.
*
* Returns 0 on success or -1 on failure.
*/
int json2avro (Serdes::Schema *schema, const std::string &json,
avro::GenericDatum **datump) {
avro::ValidSchema *avro_schema = schema->object();
/* Input stream from json string */
std::istringstream iss(json);
auto json_is = avro::istreamInputStream(iss);
/* JSON decoder */
avro::DecoderPtr json_decoder = avro::jsonDecoder(*avro_schema);
avro::GenericDatum *datum = new avro::GenericDatum(*avro_schema);
try {
/* Decode JSON to Avro datum */
json_decoder->init(*json_is);
avro::decode(*json_decoder, *datum);
} catch (const avro::Exception &e) {
std::cerr << "% JSON to Avro transformation failed: "
<< e.what() << std::endl;
return -1;
}
*datump = datum;
}
int main (int argc, char* argv) {
izycoinstestavro::fh_price_t price{};
price.s = "BTCUSDT";
price.c = "spread";
price.u = 123456789;
price.a = 20000.4;
price.A = 1.25;
price.b = 21000.52;
price.B = 0.58;
price.p = -1;
price.P = -1;
price.st = -1;
price.rt = 1675000000123000;
std::ifstream file_ifstream("../src/avro/fh_price_t.json");
std::stringstream buffer;
buffer << file_ifstream.rdbuf();
std::string schema_json = buffer.str();
Serdes::Conf *sconf = Serdes::Conf::create();
Serdes::Schema *schema;
std::string errstr;
if (sconf->set("schema.registry.url", "http://localhost:8081", errstr))
FATAL("Conf failed: " << errstr);
if (sconf->set("serializer.framing", "cp1", errstr))
FATAL("Conf failed: " << errstr);
Serdes::Avro *serdes = Serdes::Avro::create(sconf, errstr);
if (!serdes)
FATAL("Failed to create Serdes handle: " << errstr);
schema = Serdes::Schema::add(serdes, "fh_price_t", schema_json, errstr);
if (!schema)
FATAL("Failed to register schema " << "fh_price_t" << ": " << errstr);
std::cout << "% Registered schema " << schema->name() << " with id " << schema->id() << std::endl;
avro::GenericDatum *datum = NULL;
std::vector<char> out;
/* Convert JSON to Avro object */
std::string line = to_string_a(price);
json2avro(schema, line, &datum);
//std::cout << to_string_a(price) << std::endl;
/*if (rr == -1) {
FATAL("Failed to convert JSON to Avro " << to_string_a(price) << ": " << errstr);
}
// Serialize Avro
if (serdes->serialize(schema, datum, out, errstr) == -1) {
std::cerr << "% Avro serialization failed: " << errstr << std::endl;
delete datum;
exit(1);
}
delete datum;
std::cout << "Data Size : " << out.size() << std::endl;*/
return 0;
}
When I run it, I get a double free or corruption (out) error.
The error occurs at the output of the function.
I have located the line that causes the error (because when I remove it, the error disappears)
avro::GenericDatum *datum = new avro::GenericDatum(*avro_schema);
I would like to know why and how to solve it.

Open 2 distinct sockets to 1 common remote endpoint using Boost::asio

I am trying to test sending data from 2 distinct network adapters on the same machine to a common remote endpoint, but I keep getting "bind: invalid argument" AFTER the first bind comes through. What am I missing? I have searched, tried to modify the code, but I was not able to find any lead and I keep getting the same error. The same happens when I swap out the IPs.
#include <iostream>
#include <boost/asio.hpp>
#include <sstream>
#include <thread>
#include <chrono>
#include <boost/random.hpp>
const unsigned int MS_INTERVAL = 100;
enum CMD_ARG
{
PROG_NAME = 0,
LOCAL_IP_1,
LOCAL_IP_2,
REMOTE_IP,
REMOTE_PORT
};
using namespace boost::asio;
using std::string;
using std::cout;
using std::endl;
int main(int argc, char *argv[]) {
if(argc == 5)
{
//Test data initialisation
unsigned int counter = 0;
boost::random::mt19937 randSeed; // seed, produces randomness out of thin air
boost::random::uniform_int_distribution<> randGen(-1000,1000); // Random number generator between -100 and 100
//Initialise ASIO service
io_service io_service;
//socket creation and binding (one per network adapter)
std::cout << "Opening and binding local sockets to " << argv[LOCAL_IP_1] << " and " << argv[LOCAL_IP_2] << std::endl;
ip::tcp::socket socket1(io_service);
ip::tcp::socket socket2(io_service);
socket1.open(ip::tcp::v4());
socket2.open(ip::tcp::v4());
socket1.bind(ip::tcp::endpoint(ip::address::from_string(argv[LOCAL_IP_1]), 0));
std::cout << "1/2 done" << std::endl;
socket2.bind(ip::tcp::endpoint(ip::address::from_string(argv[LOCAL_IP_2]), 0));
//Connection to remote end point starting with defining the remote endpoint
std::istringstream iss(argv[REMOTE_PORT]);
unsigned int port = 0;
iss >> port;
ip::tcp::endpoint remoteEndpoint = ip::tcp::endpoint( ip::address::from_string(argv[REMOTE_IP]), port);
std::cout << "Connecting to " << argv[REMOTE_IP] << " on port " << port << std::endl;
socket1.connect(remoteEndpoint);
std::cout << "1/2 done" << std::endl;
socket2.connect(remoteEndpoint);
std::cout << "Ready" << std::endl;
while(1)
{
//Build message
std::ostringstream oss;
oss << counter << "," << randGen(randSeed) << "," << randGen(randSeed) << "," << randGen(randSeed) << std::endl;
//Send message on both interfaces
boost::system::error_code error1, error2;
write(socket1, boost::asio::buffer(oss.str()), error1);
write(socket2, boost::asio::buffer(oss.str()), error2);
//Check errors
if( !error1 && !error2) {
cout << "Sending: " << oss.str() << endl;
counter++;
}
else {
cout << "Error: " << (error1?error1.message():error2.message()) << endl;
}
std::this_thread::sleep_for(std::chrono::milliseconds(MS_INTERVAL));
}
}
else
{
std::cout << "Usage: <program> <local IP 1> <local IP 2> <remote server IP> <server's opened port>" << argc << std::endl;
}
return 0;
}
socket1.bind(ip::tcp::endpoint(ip::address::from_string(argv[LOCAL_IP_1]), 0));
...
socket1.bind(ip::tcp::endpoint(ip::address::from_string(argv[LOCAL_IP_2]), 0));
You are trying to bind the same socket1 twice. Likely you mean socket2 in the second statement.

Can the NETLINK/SOCK_DIAG interface be used to listen for `listen()` and `close()` events of said socket?

I've been gleaning information about the NETLINK socket which allows us to listen on what is happening in socket land. It seems to very partially work, but I'm wondering whether I missed something.
I'm using C++, although of course all the NETLINK is pure C, so here we have mainly C headers. The following code has three main parts:
Binding
First I create a socket() and bind() it.
The bind() is kind of magical. When using a bound NETLINK socket, you start receiving events without having to have a polling setup (which is why I'm trying to do this, to avoid polling for when a socket starts listening for connections).
I put -1 in the nl_groups so that way all events are sent to my socket. But, at this point, I seem to only receive two of them: TCP_ESTABLISHED and TCP_CLOSE. The one I really would like to receive is the TCP_LISTEN and "not listening" (which apparently is not going to be available...)
Explicit Request
I tried with an explicit request. I have it in the code below so you can see how I've done it. That request works as expected. I get an explicit reply if the socket exists or an error "No such file or directory" when the socket is closed. Great, except that mechanism means I'd be using a poll (i.e. I need my process to try over and over again on a timer until the socket is visible).
Note: the error when no one is listening is happening because the request is explicit, i.e. it includes the expected IP address and port that I'm interested in.
Response
The next part is a loop, which sits until a response is received. The recvmsg() call is blocking in this version, which is why it sits around in this test.
If I sent my explicit request (see point 2. above), then, as I mentioned, I get a reply if another process is listening, otherwise I get an error saying it's not listening. The state is clearly set to 10 (TCP_LISTEN), so everything works as expected.
When listening to all the events (-1 in the bind), the process will go on and receive more data as events happen. However, so far, the only events I've received are 1 and 7 (i.e. TCP_ESTABLISHED and TCP_CLOSE).
I used the following to compile my code:
g++ -Wall -o a test.cpp
Here is my test code with which I can reproduce my current results:
#include <iostream>
#include <linux/netlink.h>
#include <errno.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <linux/netlink.h>
#include <linux/rtnetlink.h>
#include <linux/sock_diag.h>
#include <linux/inet_diag.h>
int
main(int argc, char ** argv)
{
// socket / bind
int d = socket(AF_NETLINK, SOCK_RAW, NETLINK_SOCK_DIAG);
if(d < 0)
{
std::cerr << "error: could not create RAW socket.\n";
return 1;
}
struct sockaddr_nl addr = {};
addr.nl_family = AF_NETLINK;
addr.nl_pid = getpid();
addr.nl_groups = -1;
// You can find these flags in Linux source:
//
// "/usr/src/linux-headers-4.15.0-147/include/net/tcp_states.h
//
// (1 << 7) // TCPF_CLOSE
// | (1 << 8) // TCPF_CLOSE-WAIT
// | (1 << 10) // TCPF_LISTEN
// | (1 << 11) // TCPF_CLOSING
// ;
if(bind(d, reinterpret_cast<struct sockaddr *>(&addr), sizeof(addr)) != 0)
{
perror("bind failure\n");
return 1;
}
// request
struct sockaddr_nl nladdr = {};
nladdr.nl_family = AF_NETLINK;
struct nl_request
{
struct nlmsghdr f_nlh;
struct inet_diag_req_v2 f_inet;
};
nl_request req = {};
req.f_nlh.nlmsg_len = sizeof(req);
req.f_nlh.nlmsg_type = SOCK_DIAG_BY_FAMILY;
req.f_nlh.nlmsg_flags = NLM_F_REQUEST;
req.f_inet.sdiag_family = AF_INET;
req.f_inet.sdiag_protocol = IPPROTO_TCP;
req.f_inet.idiag_ext = 0;
req.f_inet.pad = 0;
req.f_inet.idiag_states = 0;
req.f_inet.id.idiag_sport = htons(4998);
req.f_inet.id.idiag_dport = 0;
req.f_inet.id.idiag_src[0] = htonl(0x0A00020A);
req.f_inet.id.idiag_dst[0] = 0;
req.f_inet.id.idiag_if = 0;
req.f_inet.id.idiag_cookie[0] = INET_DIAG_NOCOOKIE;
req.f_inet.id.idiag_cookie[1] = INET_DIAG_NOCOOKIE;
struct iovec vector = {};
vector.iov_base = &req;
vector.iov_len = sizeof(req);
struct msghdr msg = {};
msg.msg_name = &nladdr;
msg.msg_namelen = sizeof(nladdr);
msg.msg_iov = &vector;
msg.msg_iovlen = 1;
int const r(sendmsg(d, &msg, 0));
if(r < 0)
{
perror("sendmsg");
return 1;
}
// response
struct sockaddr_nl r_nladdr = {};
r_nladdr.nl_family = AF_NETLINK;
struct iovec r_vector = {};
long buf[8192 / sizeof(long)];
r_vector.iov_base = buf;
r_vector.iov_len = sizeof(buf);
for(int i(1);; ++i)
{
struct msghdr r_msg = {};
r_msg.msg_name = &r_nladdr;
r_msg.msg_namelen = sizeof(r_nladdr);
r_msg.msg_iov = &r_vector;
r_msg.msg_iovlen = 1;
//std::cout << "wait for message...\n";
ssize_t size(recvmsg(d, &r_msg, 0));
if(size < 0)
{
perror("recvmsg");
return 1;
}
if(size == 0)
{
std::cout << "end of message stream received." << std::endl;
break;
}
//std::cout << "got message #" << i << ": size = " << size << std::endl;
struct nlmsghdr const * h(reinterpret_cast<struct nlmsghdr *>(buf));
if(!NLMSG_OK(h, size))
{
std::cerr << "NLMSG_OK() says there is an error." << std::endl;
return 1;
}
do
{
if(h->nlmsg_type == NLMSG_DONE)
{
std::cout << "explicit end of message stream received (NLMSG_DONE)." << std::endl;
break;
}
if(h->nlmsg_type == NLMSG_ERROR)
{
struct nlmsgerr const * err(reinterpret_cast<struct nlmsgerr const *>(NLMSG_DATA(h)));
if(h->nlmsg_len < NLMSG_LENGTH(sizeof(*err)))
{
std::cerr << "unknown NLMSG_ERROR received." << std::endl;
}
else
{
// here is the location display an error when trying to get an
// event about the LISTEN and no one is listening on that port.
//
errno = -err->error;
perror("NLMSG_ERROR:");
}
return 1;
}
if(h->nlmsg_type != SOCK_DIAG_BY_FAMILY)
{
std::cerr << "unexpected message type (h->nlmsg_type) "
<< h->nlmsg_type
<< std::endl;
return 1;
}
//std::cout << "------- sock_diag info!\n";
struct inet_diag_msg const * k_msg(reinterpret_cast<struct inet_diag_msg const *>(NLMSG_DATA(h)));
if(h->nlmsg_len < NLMSG_LENGTH(sizeof(*k_msg)))
{
std::cerr << "unexpected message length (h->nlmsg_len) "
<< h->nlmsg_type
<< std::endl;
return 1;
}
switch(k_msg->idiag_state)
{
case 1:
case 7:
break;
default:
{
std::uint32_t const src_ip(ntohl(k_msg->id.idiag_src[0]));
std::uint32_t const dst_ip(ntohl(k_msg->id.idiag_dst[0]));
std::cout << "inet_diag_msg->idiag_family = " << static_cast<int>(k_msg->idiag_family) << "\n"
<< "inet_diag_msg->idiag_state = " << static_cast<int>(k_msg->idiag_state) << "\n"
<< "inet_diag_msg->idiag_timer = " << static_cast<int>(k_msg->idiag_timer) << "\n"
<< "inet_diag_msg->idiag_retrans = " << static_cast<int>(k_msg->idiag_retrans) << "\n"
<< "inet_diag_msg->id.idiag_sport = " << ntohs(k_msg->id.idiag_sport) << "\n"
<< "inet_diag_msg->id.idiag_dport = " << ntohs(k_msg->id.idiag_dport) << "\n"
<< "inet_diag_msg->id.idiag_src[0] = " << ((src_ip >> 24) & 255)
<< "." << ((src_ip >> 16) & 255) << "." << ((src_ip >> 8) & 255) << "." << (src_ip & 255) << "\n"
<< "inet_diag_msg->id.idiag_dst[0] = " << ((dst_ip >> 24) & 255)
<< "." << ((dst_ip >> 16) & 255) << "." << ((dst_ip >> 8) & 255) << "." << (dst_ip & 255) << "\n"
<< "inet_diag_msg->id.idiag_if = " << k_msg->id.idiag_if << "\n"
<< "inet_diag_msg->id.idiag_cookie[0] = " << k_msg->id.idiag_cookie[0] << "\n"
<< "inet_diag_msg->id.idiag_cookie[1] = " << k_msg->id.idiag_cookie[1] << "\n"
<< "inet_diag_msg->idiag_expires = " << k_msg->idiag_expires << "\n"
<< "inet_diag_msg->idiag_rqueue = " << k_msg->idiag_rqueue << "\n"
<< "inet_diag_msg->idiag_wqueue = " << k_msg->idiag_wqueue << "\n"
<< "inet_diag_msg->idiag_uid = " << k_msg->idiag_uid << "\n"
<< "inet_diag_msg->idiag_inode = " << k_msg->idiag_inode << "\n"
<< "\n";
}
break;
}
// next message
//
h = NLMSG_NEXT(h, size);
}
while(NLMSG_OK(h, size));
}
return 0;
}
To test that IP:port combo, I simply used the nc command like so:
nc -l 10.0.2.10 4998
You of course need the 10.0.2.10 IP on one of your interfaces for this to work.
My question is:
Did I do something wrong that I do not receive TCP_LISTEN events on that socket unless explicitly requested?
P.S. Just in case, I tried to run this test app as root. Same results.

RtMidi - MidiInDummy: This class provides no functionality

I want to use Rtmidi to get input from launchpad.
However, despite connecting the launchpad, 0 pods are available.
"MidiInDummy: This class providers no functionality."
There's also this phrase, so something seems to be wrong.
Source:
//Source : http://www.music.mcgill.ca/~gary/rtmidi/index.html#probing
#define __WINDOWS_MM__
#include <iostream>
#include <cstdlib>
#include "RtMidi.h"
int main()
{
RtMidiIn* midiin = 0;
RtMidiOut* midiout = 0;
// RtMidiIn constructor
try {
midiin = new RtMidiIn();
}
catch (RtMidiError& error) {
error.printMessage();
exit(EXIT_FAILURE);
}
// Check inputs.
unsigned int nPorts = midiin->getPortCount();
std::cout << "\nThere are " << nPorts << " MIDI input sources available.\n";
std::string portName;
for (unsigned int i = 0; i < nPorts; i++) {
try {
portName = midiin->getPortName(i);
}
catch (RtMidiError& error) {
error.printMessage();
goto cleanup;
}
std::cout << " Input Port #" << i + 1 << ": " << portName << '\n';
}
// RtMidiOut constructor
try {
midiout = new RtMidiOut();
}
catch (RtMidiError& error) {
error.printMessage();
exit(EXIT_FAILURE);
}
// Check outputs.
nPorts = midiout->getPortCount();
std::cout << "\nThere are " << nPorts << " MIDI output ports available.\n";
for (unsigned int i = 0; i < nPorts; i++) {
try {
portName = midiout->getPortName(i);
}
catch (RtMidiError& error) {
error.printMessage();
goto cleanup;
}
std::cout << " Output Port #" << i + 1 << ": " << portName << '\n';
}
std::cout << '\n';
// Clean up
cleanup:
delete midiin;
delete midiout;
return 0;
}
Output:
MidiInDummy: This class provides no functionality.
There are 0 MIDI input sources available.
MidiOutDummy: This class provides no functionality.
There are 0 MIDI output ports available.
How can I solve this problem?
Oh, I solved it.
https://www.music.mcgill.ca/~gary/rtmidi/#compiling
https://github.com/thestk/rtmidi/issues/85
keyword : __WINDOWS_MM__, winmm.lib

How to set autoreconnect option with mysql connector c++

Greetings, how can i set autoReconnect option with mysql connector c++ ?
( not with mysql c api http://dev.mysql.com/doc/refman/5.0/en/mysql-options.html )
I am not a user of this library, so my knowledge of it is only that last 10 mins worth, so please do verify.
As a general rule, the best resource of such information about usage of various specific details of a library is to take a look at its unit tests. The best thing about OSS.
So if you look at MySQL Connector/C++ unit tests that can be found on their source tree, you will see the below extract.
sql::ConnectOptionsMap connection_properties;
...
connection_properties["OPT_RECONNECT"]=true;
try
{
con.reset(driver->connect(connection_properties));
}
catch (sql::SQLException &e)
{
std::cerr << e.what();
}
For more information, please do the below, so that you can take a look yourselves.
~/tmp$ bzr branch lp:~mysql/mysql-connector-cpp/trunk mysql-connector-cpp
~/tmp$ vi mysql-connector-cpp/test/unit/classes/connection.cpp +170
~/tmp$ vi mysql-connector-cpp/test/unit/classes/connection.h
Having said all that, reconnect option in mysql has to be used very carefully, as you will have to reset any session variables, etc. You will have to treat a reconnected connection as a brand new connection. This has to be verified with the documentation of the particular version of MySQL you are working with.
A more complete example
header
#include <boost/thread.hpp>
#include <boost/shared_ptr.hpp>
#include <mysql_connection.h>
#include <cppconn/driver.h>
#include <cppconn/exception.h>
#include <cppconn/resultset.h>
#include <cppconn/statement.h>
#include <cppconn/prepared_statement.h>
std::string host_name = "localhost";
std::string user_name = "user1234";
std::string password = "pw1234";
std::string database_name = "TestingDB";
bool reconnect_state = true;
sql::ConnectOptionsMap connection_properties;
sql::Driver *driver;
boost::shared_ptr <sql::Connection> con;
boost::shared_ptr <sql::Statement> stmt;
boost::shared_ptr <sql::ResultSet> res;
boost::shared_ptr <sql::PreparedStatement> pstmt;
connect
driver = get_driver_instance (); // protected
con.reset(driver->connect (host_name, user_name, password)); // connect to mysql
con->setClientOption("OPT_RECONNECT", &reconnect_state);
con->setSchema(database_name);
thread
std::vector <std::string> database::string_from_sql (std::string query, std::string column_name)
{
std::cout << __FILE__ << "(" << __FUNCTION__ << ":" << __LINE__ << ") | started" << std::endl;
std::vector <std::string> svec;
try
{
driver->threadInit(); // prevents multiple open connections
if (con.get() == NULL)
{
std::cerr << __FILE__ << "(" << __FUNCTION__ << ":" << __LINE__ << ") | connection is not open" << std::endl;
throw -2;
}
stmt.reset (con->createStatement ());
res.reset (stmt->executeQuery (query));
while (res->next())
{
svec.push_back(res->getString (column_name));
}
driver->threadEnd();
}
catch (sql::SQLException &e)
{
std::cerr << __FILE__ << "(" << __FUNCTION__ << ":" << __LINE__ << ") | e.what(): " << e.what() << " (MySQL error code: " << e.getErrorCode() << ", SQLState: " << e.getSQLState() << " )" << std::endl;
throw -1;
}
if (svec.empty())
{
std::cerr << __FILE__ << "(" << __FUNCTION__ << ":" << __LINE__ << ") | return vector size is 0 (Empty set)" << std::endl;
throw -3;
}
std::cout << __FILE__ << "(" << __FUNCTION__ << ":" << __LINE__ << ") | ended" << std::endl;
return svec;
}
You need to pass the boolean value by reference. My code does:
bool myTrue = true;
con->setClientOption("OPT_RECONNECT", &myTrue);
And that worked for me.