STOP PRESS! The full book is now available DIRECTLY from Amazon with lower shipping costs!
This program allows the user to type in a line of text. It then breaks the text up into packets, as if it were about to be sent over the Internet. Each packet has some header information added to it: the IP address of the sender, the IP address of the packet destination, the packet number and the total number of packets that make up the message.
Select and copy the C++ source-code at the bottom of this post.
Paste into a text editor, such as Nano or Geany.
Then save the new file, ending in .cpp
I used packets.cpp
To compile from the command-line:
g++ -o packets.cpp packets
To run from the command-line:
./packets
Here's the code:
#include <iostream> // Uses keyboard input and screen output
using namespace std; // Uses standard names cout, cin, endl
int main()
{
const int PACKET_SIZE = 8;
const string SENDER_IP = "128.65.127.1";
const string DESTINATION_IP = "10.45.110.190";
// Allow user to type in a message to send across Internet
cout << "Type in your message to send:" << endl;
string message;
getline(cin, message);
// Split the text message into packets of data,
// add data about sender, destination, packet number and total
int lengthOfMessage = message.length();
int totalPacketsNeeded = lengthOfMessage / PACKET_SIZE;
if ( lengthOfMessage % PACKET_SIZE > 0 )
totalPacketsNeeded++;
int packetsMadeSoFar = 0;
string packetData;
string wholePacket;
// Repeatedly create packets until whole message processed
while ( packetsMadeSoFar * PACKET_SIZE < lengthOfMessage )
{
// Chop up text to put in packet
packetData = message.substr( packetsMadeSoFar*PACKET_SIZE, PACKET_SIZE);
cout << "\e[32m"; // Turn text green
cout << SENDER_IP << " ";
cout << "\e[38;5;226m"; // Turn text yellow
cout << DESTINATION_IP << " ";
cout << "\e[31m"; // Turn text red
cout << packetsMadeSoFar << " ";
cout << "\e[35m"; // Turn text magenta
cout << totalPacketsNeeded << " ";
cout << "\e[0m"; // Reset text colours
cout << packetData << endl;
packetsMadeSoFar++;
} // end of while loop
return 0;
}
Find out more - buy the book on Amazon!