From 8f64449117b03b51f77b4b9558098187cb1978c0 Mon Sep 17 00:00:00 2001 From: Erik Frojdh Date: Tue, 4 Feb 2020 17:34:07 +0100 Subject: [PATCH] initial fixing --- sample/CMakeLists.txt | 16 ++++++++- sample/udp.cpp | 13 +++++++ slsSupportLib/include/UdpSocket.h | 56 +++++++++++++++++++++++++++++++ 3 files changed, 84 insertions(+), 1 deletion(-) create mode 100644 sample/udp.cpp create mode 100644 slsSupportLib/include/UdpSocket.h diff --git a/sample/CMakeLists.txt b/sample/CMakeLists.txt index ff1835f63..86481eadc 100644 --- a/sample/CMakeLists.txt +++ b/sample/CMakeLists.txt @@ -18,4 +18,18 @@ target_link_libraries(result set_target_properties(result PROPERTIES RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bin -) \ No newline at end of file +) + +add_executable(udp udp.cpp) +target_link_libraries(udp + slsDetectorShared + slsSupportLib + pthread + rt +) + +set_target_properties(udp PROPERTIES + RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bin +) + + diff --git a/sample/udp.cpp b/sample/udp.cpp new file mode 100644 index 000000000..fbcb7fbb7 --- /dev/null +++ b/sample/udp.cpp @@ -0,0 +1,13 @@ +#include "UdpSocket.h" +#include +#include +#include +int main(){ + std::cout << "HEJ\n"; + sls::UdpSocket s(50010, 1024); + + while(true){ + std::cout << "Got: " << s.ReceivePacket() << " bytes\n"; + std::this_thread::sleep_for(std::chrono::milliseconds(5)); + } +} \ No newline at end of file diff --git a/slsSupportLib/include/UdpSocket.h b/slsSupportLib/include/UdpSocket.h new file mode 100644 index 000000000..d1a8dd8b3 --- /dev/null +++ b/slsSupportLib/include/UdpSocket.h @@ -0,0 +1,56 @@ + +#include +#include +#include +#include +#include +#include +#include +#include + +#include "sls_detector_exceptions.h" + +namespace sls { + +class UdpSocket { + int port; + size_t packet_size; + size_t buffer_size; + int fd = -1; + + public: + UdpSocket(int port, size_t packet_size) + : port(port), packet_size(packet_size) { + const char *hostname = 0; /* wildcard */ + const std::string portname = std::to_string(port); + struct addrinfo hints; + memset(&hints, 0, sizeof(hints)); + hints.ai_family = AF_UNSPEC; + hints.ai_socktype = SOCK_DGRAM; + hints.ai_protocol = 0; + hints.ai_flags = AI_PASSIVE | AI_ADDRCONFIG; + struct addrinfo *res = 0; + if (getaddrinfo(hostname, portname.c_str(), &hints, &res)){ + throw RuntimeError("Failed getaddinfo"); + } + fd = socket(res->ai_family, res->ai_socktype, res->ai_protocol); + if(fd==-1){ + throw RuntimeError("Failed creating socket"); + } + if (bind(fd, res->ai_addr, res->ai_addrlen) == -1) { + throw RuntimeError("Failed to bind socket"); + } + freeaddrinfo(res); + } + + int ReceivePacket() { + char buffer[549]; + struct sockaddr_storage src_addr; + socklen_t src_addr_len = sizeof(src_addr); + ssize_t count = recvfrom(fd, buffer, sizeof(buffer), 0, + (struct sockaddr *)&src_addr, &src_addr_len); + return count; + } +}; + +} // namespace sls \ No newline at end of file