/* a C++ socket server class Keith Vertanen 11/98 */ #include "server.h" #define BACKLOG 10 // how many pending connections queue will hold #define VERBOSE 1 // turn on or off debugging output Server::Server(int p, int datap) { port = p; dataport = datap; if (VERBOSE) printf("Server: opening socket on port = %d, datagrams on port = %d\n", port, dataport); if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) == -1) { perror("socket"); exit(1); } if ((datasockfd = socket(AF_INET, SOCK_DGRAM, 0)) == -1) { perror("datagram socket"); exit(1); } if ((senddatasockfd = socket(AF_INET, SOCK_DGRAM, 0)) == -1) { perror("datagram send socket"); exit(1); } my_addr.sin_family = AF_INET; /* host byte order */ my_addr.sin_port = htons(port); /* short, network byte order */ my_addr.sin_addr.s_addr = INADDR_ANY; /* auto-fill with my IP */ bzero(&(my_addr.sin_zero), 8); /* zero the rest of the struct */ if (bind(sockfd, (struct sockaddr *)&my_addr, sizeof(struct sockaddr)) == -1) { exit(1); } my_addr.sin_port = htons(dataport); if (bind(datasockfd, (struct sockaddr *)&my_addr, sizeof(struct sockaddr)) == -1) { exit(1); } if (listen(sockfd, BACKLOG) == -1) { exit(1); } }; // wait for somebody to connect to us on our port void Server::connect() { struct hostent *he; char hostname[80]; int len; sin_size = sizeof(struct sockaddr_in); if ((new_fd = accept(sockfd, (struct sockaddr *)&their_addr, &sin_size)) == -1) { perror("accept"); } if (VERBOSE) printf("Server: got connection from %s\n", inet_ntoa(their_addr.sin_addr)); // the dest_addr is used by the send_datagram method // their_addr seems about the same, but it doesn't work // and when I put this in, it started working, hmmmm dest_addr.sin_family = AF_INET; dest_addr.sin_port = htons(dataport); dest_addr.sin_addr = their_addr.sin_addr; bzero(&(dest_addr.sin_zero), 8); // the client sends us an int to indicate if we should // be reversing byte order on this connection // the client is sending 0 or 1, so a reversed 0 still looks // like a 0, no worries mate! char temp[1]; int total = 0; while (total<1) total += recv(new_fd, temp, 1, 0); int val = temp[0]; if (val==0) REVERSE = 0; else REVERSE = 1; if (VERBOSE) if (val==0) { printf("Client requested normal byte order.\n"); } else { printf("Client requested reversed byte order.\n"); } }; // send a string to the socket void Server::send_string(char *str) { if (send(new_fd, (char *) str, strlen(str), 0) == -1) perror("send"); if (VERBOSE) printf("Server: sending string '%s'\n", str); recv_ack(); send_ack(); }; // send some bytes over the wire void Server::send_bytes(char *val, int len) { int i; if (send(new_fd, (char *) val, len, 0) == -1) perror("send bytes"); if (VERBOSE) { printf("Server: sending %d bytes - ", len); for (i=0; i