Socket Programming, step out of the neophyte stage. CPP version

7 replies [Last post]
revall
revall's picture
Offline
SX VIP
Joined: 2014/09/29

One of the most important ascpects in programming is to be able to let your programms talk to, configure, or monitor networks. This can be used to test a servers conectivity on the fly, or set up a server on a target machine so you can connect to it remotely.

You will not always have access to a tool that someone else made. So my hopes with this tut is that you can learn to roll your own tools out on the fly. I will start these string of tuts out with a simple tcp client. This program will send an HTTP request to a server and listen for a response. This is a good way to quickly test the status of a server.

Read each line of code, and the comments should help explain what each line does. There will be a more detailed tut for this on Turorials page. This is also where I will post all following tutorials.

Lets get started:

NOTE: The Code following is for linux.

CPP code

#include
#include
#include //Needed to create the socket. Gives access to system commands for sockets
#include //Needed for socket
#include //Since gcc 4.7 you now need this to close socket

using namespace std;

int main()
{
int connStatus; //Store the status for the server info population
struct addrinfo host_info; // The struct that getaddrinfo() uses
struct addrinfo *host_info_list; // Set up a list for different host infos

//0 fill the struct. Make sure there is no bad data
memset(&host_info, 0, sizeof host_info);

//Set up the Structs for the Server Data.
cout << "Setting server data into the addrinfo struct.\n\n";

host_info.ai_family = AF_INET; //Set IP to handle TCP Connections
host_info.ai_socktype = SOCK_STREAM; //Sets the socket type to acccept TCP transmission

connStatus = getaddrinfo("google.com", "80", &host_info, &host_info_list); //Populates the structs with addrinfo of google on port 80

//Check if we were able to get data from the server
if(connStatus == 0) cout << "Connection information populated successfuly\n\n";
else if(connStatus != 0) cout << "Connection error: " << gai_strerror(connStatus) << endl;

cout << "Creating the socket now...";

int sock; //Descriptor for our socket

sock = socket(host_info_list->ai_family, host_info_list->ai_socktype, host_info_list->ai_protocol); //Opens internet socket with host, type, and protocol. This was all populated by getaddrinfo().

//Make sure the sock was created
if(sock == -1) cout << "Socket Error: " << endl; //Need to put error reporting in still
else cout << "Socket Created\n\n";

cout << "Connecting to the server...";
//Pass the connection code the Socket, the Address, and the Address length. return connection status
connStatus = connect(sock, host_info_list->ai_addr, host_info_list->ai_addrlen);
if(connStatus == -1) cout << "Connection Error: " << endl;
else cout << "You are now connected.\n\n";

cout << "Sending Data... \n\n";
//Msg to be sent
char *msg = "GET / HTTP/1.1\nhost: www.google.com\n\n";

int length; //Initialize msg lenghth
ssize_t bytesSent; //initialize bytesSent as a ssize_t
length = strlen(msg); //get length of msg for the buffer
//Tie to socket, send msg, give it the msg length for the buffer and set flags to 0. these are the same as write() function.
bytesSent = send(sock, msg, length, 0);

//Then we need to receive the data back from server
//The recv func will wait for a response to system.

cout << "Waiting to recieve data... \n";
ssize_t bytesReceived;
char buffer[5000]; //Set up a buffer to recveive data
bytesReceived = recv(sock, buffer, 5000, 0); //Recv data
if(bytesReceived == 0) cout << "Host disconnected.\n";
if(bytesReceived == -1) cout << "Connection error\n";
cout << bytesReceived << " bytes received :" << endl ;
cout << buffer << endl;

//If you open a door close it
cout << "Transaction success. Closing socket...\n";
freeaddrinfo(host_info_list); //Releases host information from memory
close(sock); //Closes the open socket on port 80

//That does it for this round. Not to bad to understand once you break it down.
}

Welcome, neophyte, to the real world.

Stay tuned for a python equivalent, and more tuts like this one with more advanced topics.
Plus if you have any request for tuts in this feild comment bellow to request it.
-revall