#include #include #include #include // need this for unix domain sockets. #include // unlink #include #include using namespace std; const string PATH{"/tmp/DieServer"}; const size_t BUFFER_SIZE {1024}; int main() { int theSocket; struct sockaddr_un address, server; string name; theSocket = socket(AF_UNIX, SOCK_DGRAM, 0); if(theSocket == -1) { perror("Socket failed: "); exit(1); } stringstream nameMaker; nameMaker << "/tmp/dieClient" << getpid(); name = nameMaker.str(); // try to remove the an existing socket address if (-1 == unlink(name.c_str()) and errno != ENOENT) { perror("Unlink existing socket: "); exit(1); } // set the address field memset(&address, 0, sizeof(struct sockaddr_un)); address.sun_family = AF_UNIX; strncpy(address.sun_path, name.c_str(), sizeof(address.sun_path)-1); if( -1 == bind(theSocket,reinterpret_cast( &address), sizeof(struct sockaddr_un))) { perror("Bind failed: "); } // build the address of the server. memset(&server, 0, sizeof(struct sockaddr_un)); server.sun_family = AF_UNIX; strncpy(server.sun_path, PATH.c_str(), sizeof(server.sun_path)-1); bool done{false}; char buffer[BUFFER_SIZE]; socklen_t len; size_t bytes; string cmd; while (not done) { len = sizeof(struct sockaddr_un); cout << "Enter a command for the server : "; getline(cin, cmd); if (cmd == "quit" or cmd =="stop"){ done = true; } memset(&buffer, 0, BUFFER_SIZE); strncpy(buffer, cmd.c_str(), BUFFER_SIZE); size_t size = min(BUFFER_SIZE, cmd.size()+1); bytes= sendto(theSocket, buffer, size, 0, reinterpret_cast(&server), len); if (!done) { // get the answer back memset(&buffer, 0, BUFFER_SIZE); bytes = recvfrom(theSocket, buffer, BUFFER_SIZE, 0, reinterpret_cast(&server), &len); if (bytes > 0) { buffer[bytes-1] = 0; cout << "Got \"" << buffer << "\" from " << server.sun_path << endl; } } } close(theSocket); unlink(name.c_str()); return 0; }