Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include "userver.h"
- UDPServer::UDPServer(unsigned short port)
- : m_sock{ AF_INET, SOCK_DGRAM, IPPROTO_UDP }, m_client_address{ 0 }, m_client_address_len{ sizeof(sockaddr_in) }, m_port(port), m_recv_len{ 0 } {}
- void UDPServer::listenUDP()
- {
- std::cout << "Starting echo server on the port " << m_port << "...\n";
- if (!m_sock)
- {
- std::cerr << m_sock_wrap.get_last_error_string() << std::endl;
- exit(EXIT_FAILURE);
- }
- sockaddr_in addr
- {
- .sin_family = PF_INET,
- .sin_port = htons(m_port),
- };
- addr.sin_addr.s_addr = INADDR_ANY;
- if (bind(m_sock, reinterpret_cast<const sockaddr*>(&addr), sizeof(addr)) != 0)
- {
- std::cerr << m_sock_wrap.get_last_error_string() << std::endl;
- // Socket will be closed in the Socket destructor.
- exit(EXIT_FAILURE);
- }
- std::cout << "Running echo server(Enter 'exit' to exit)...\n" << std::endl;
- const int len = 256;
- char buffer[len];
- char client_address_buf[INET_ADDRSTRLEN];
- char hbuf[NI_MAXHOST];
- bool run = true;
- while (run)
- {
- // Read content into buffer from an incoming client.
- m_recv_len = recvfrom(m_sock, buffer, sizeof(buffer) - 1, 0,
- reinterpret_cast<sockaddr*>(&m_client_address),
- &m_client_address_len);
- int x = 0;
- if (m_recv_len > 0)
- {
- buffer[m_recv_len] = '\0';
- std::cout
- << "Client with address: "
- << inet_ntop(AF_INET, &m_client_address.sin_addr, client_address_buf, sizeof(client_address_buf) / sizeof(client_address_buf[0]))
- << ":" << ntohs(m_client_address.sin_port)
- << " and host name: ";
- if (x = getnameinfo(reinterpret_cast<sockaddr*>(&m_client_address), m_client_address_len,
- hbuf, sizeof(hbuf), nullptr, 0, NI_NAMEREQD) != 0)
- {
- std::cerr << "could not resolve hostname" << std::endl;
- }
- else
- {
- std::cout << "host" << hbuf << std::endl;
- }
- std::cout << " sent datagram "
- << "[length = "
- << m_recv_len
- << "]:\n'''\n"
- << buffer
- << "\n'''"
- << std::endl;
- std::string command_string = { buffer, 0, len };
- rtrim(command_string);
- if ("exit" == command_string)
- {
- std::cout << "See you!" << std::endl;
- run = false;
- }
- // Send same content back to the client ("echo").
- sendto(m_sock, buffer, m_recv_len, 0, reinterpret_cast<const sockaddr*>(&m_client_address),
- m_client_address_len);
- }
- std::cout << std::endl;
- }
- }
- UDPServer::~UDPServer() {}
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement