75 lines
2.5 KiB
C++
75 lines
2.5 KiB
C++
/*
|
|
Copyright (c) 2014 IOnU Security Inc. All rights reserved
|
|
Created February 2014 by Kendrick Webster
|
|
|
|
UdpIpc.h - header for UDP-based inter-process communication
|
|
*/
|
|
#pragma once
|
|
#include <string.h>
|
|
#include "Network.h"
|
|
|
|
namespace ionu { namespace udp_ipc {
|
|
|
|
constexpr uint16_t PORT_DYNAMIC = 0; // for InitSocket
|
|
constexpr uint16_t PORT_LOOPBACK = 0; // for SendTo
|
|
|
|
// Initialize the UDP socket to listen on <port> (host byte order, 0 for dynamic)
|
|
// with socket timeout set to <timeout_milliseconds>. Logs messages indicating result
|
|
// (port number that was bound) or error details if an error occurs. Use <Log::ignore>
|
|
// to suppress log output, if desired.
|
|
success_t InitSocket(uint16_t port, uint32_t timeout_milliseconds,
|
|
Log::severity_t trace_loglevel = Log::informational, // severity for logging bound address
|
|
Log::severity_t error_loglevel = Log::error); // severity for logging errors
|
|
|
|
|
|
// Sends message <s> to destination <a> via UDP best-effort delivery.
|
|
// Returns <SUCCESS> if a message was sent, logs reason for failure otherwise.
|
|
// If a catestrophic failure occurs, logs a message and calls exit(EXIT_FAILURE).
|
|
success_t SendTo(ionu::network::CAddress a, const std::string& s);
|
|
|
|
inline success_t SendTo(ionu::network::CAddress a, const std::string& s1, const std::string& s2)
|
|
{
|
|
std::string s(s1);
|
|
s += s2;
|
|
return SendTo(a, s);
|
|
}
|
|
|
|
inline success_t SendToSelf(const std::string& s)
|
|
{
|
|
ionu::network::CAddress a;
|
|
return SendTo(a, s);
|
|
}
|
|
|
|
inline success_t SendToSelf(const std::string& s1, const std::string& s2)
|
|
{
|
|
std::string s(s1);
|
|
s += s2;
|
|
return SendToSelf(s);
|
|
}
|
|
|
|
// Checks for a received message, blocks for at most InitSocket( <timeout_milliseconds> ).
|
|
// If a message was received, returns <true> with source address in <a> and message in <s>.
|
|
// If a catestrophic failure occurs, logs a message and calls exit(EXIT_FAILURE).
|
|
bool ReceiveFrom(ionu::network::CAddress& a, std::string& s);
|
|
|
|
|
|
// String splitter for IPC message subfields
|
|
constexpr char MESSAGE_FIELD_DELIMITER = ':';
|
|
inline void SplitString(const std::string& s, std::string& s1, std::string& s2)
|
|
{
|
|
const char* p = s.c_str();
|
|
const char* q = strchr(p, MESSAGE_FIELD_DELIMITER);
|
|
if (q)
|
|
{
|
|
s1.assign(p, q - p);
|
|
s2 = q + 1;
|
|
}
|
|
else
|
|
{
|
|
s1 = s;
|
|
s2 = "";
|
|
}
|
|
}
|
|
|
|
}}
|