#include #include #include #include #include using namespace std; const int BUFFER_SIZE{1000}; const string SOCKET_PATH{"/tmp/msgServer"}; int main() { int socketFD{socket(AF_UNIX,SOCK_DGRAM, 0)}; if (socketFD == -1) { perror("Error socket: "); return 1; } struct sockaddr_un address; int addrLen = sizeof(struct sockaddr_un); memset(&address, 0, addrLen); address.sun_family = AF_UNIX; strncpy(address.sun_path, SOCKET_PATH.c_str(), sizeof(address.sun_path)-1); // may have an error. unlink(SOCKET_PATH.c_str()); if (bind(socketFD, reinterpret_cast(&address), addrLen) == -1) { perror("Error bind: "); close(socketFD); unlink(SOCKET_PATH.c_str()); return 1; } bool done = false; size_t numBytes; char buffer[BUFFER_SIZE]; struct sockaddr_un clientAddress; socklen_t len; while(not done) { len = addrLen; memset (buffer, 0, BUFFER_SIZE); numBytes = recvfrom (socketFD, buffer, BUFFER_SIZE, 0, reinterpret_cast(&clientAddress), &len); if (numBytes == -1) { perror("Error recvfrom: "); done = true; } cout << " I got " << numBytes << " bytes from " << clientAddress.sun_path << " \"" << buffer << '\"' << endl; if (strcmp(buffer, "quit") == 0) { done = true; } if(-1 == sendto(socketFD, buffer, numBytes,0, reinterpret_cast(&clientAddress), len)) { perror("Error sendto: "); } } cout << "Got a quit message, exiting" << endl; close(socketFD); unlink(SOCKET_PATH.c_str()); return 0; }