Dave explain exactly what this code does
And suggest ways it can be improved... Please.
#include
#include
#include
#include
#include
#include
const int PORT = 8080;
std::string textToBinary(const std::string& text) {
std::string binaryCode;
for (char c : text) {
std::bitset<8> bits(c);
binaryCode += bits.to_string();
}
return binaryCode;
}
int main() {
std::string text;
std::cout << "Entereth thine text: ";
std::getline(std::cin >> std::ws, text);
std::string binaryCode = textToBinary(text);
// Create socket
int sock = socket(AF_INET, SOCK_STREAM, 0);
if (sock == -1) {
std::cerr << "My liege, we hath failed. " << std::endl;
return 1;
}
// Set up the server address
sockaddr_in serverAddress;
serverAddress.sin_family = AF_INET;
serverAddress.sin_port = htons(PORT);
std::string serverIP = "127.0.0.1";
// ^ Default IP address
bool validIP = false;
while (!validIP) {
std::cout << "Entereth the receiver's IP address (default: 127.0.0.1): ";
std::cin >> serverIP;
if (inet_pton(AF_INET, serverIP.c_str(), &(serverAddress.sin_addr)) <= 0) {
std::cerr << "There appears to be no one home. Wouldst thou like to try aga'n? (Yes/No): ";
std::string tryAgain;
std::cin >> tryAgain;
if (tryAgain != "Yes" && tryAgain != "yes" && tryAgain != "Y" && tryAgain != "y") {
return 1;
}
} else {
validIP = true;
}
}
// Connect to the server
if (connect(sock, reinterpret_cast(&serverAddress), sizeof(serverAddress)) < 0) {
std::cerr << "Connection hath failed" << std::endl;
return 1;
}
// Send binary code
if (send(sock, binaryCode.c_str(), binaryCode.size(), 0) < 0) {
std::cerr << "Thine data is in limbo." << std::endl;
return 1;
}
// Close socket
close(sock);
std::cout << "HAZAA!" << std::endl;
return 0;
}