dieClient.cpp

URL: https://mirkwood.cs.edinboro.edu/~bennett/class/cmsc4000/spring2026/notes/ch3/code/dieClient.cpp
 
#include <iostream>
#include <string>
#include <sys/socket.h>
#include <sys/un.h>  // need this for unix domain sockets.
#include <unistd.h> // unlink
#include <stdio.h>
#include <sstream>

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<struct sockaddr *>( &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<struct sockaddr *>(&server), len);
  
         if (!done) {
             // get the answer back  
             memset(&buffer, 0, BUFFER_SIZE);
             bytes = recvfrom(theSocket, buffer, BUFFER_SIZE, 0,
                   reinterpret_cast<struct sockaddr *>(&server), &len);
            if (bytes > 0) {
                buffer[bytes-1] = 0;
                cout << "Got \"" << buffer << "\"  from "
                     << server.sun_path << endl;
                cout << endl;
            }
         }
     }

     close(theSocket);
     unlink(name.c_str());

     return 0;
}