Winsock c++ server app

Screendump of the server application

In this project I build a Windows application in c++ that can do some networking tasks. The application can start a webserver and that will be handy for testing purposes in the near future. In a future project I will create an android application to control a microcontroller via TCP/IP. To test this android application the webserver comes in handy to check which bytes are actually send or received. Some other features are a DNS resolver to get an IP address corrosponding to a site, a TCP/IP client that works a bit like a telnet client and an option to check the network services running in the background of the computer. This last feature comes in handy in cases where you can’t make an TCP/IP connection because some service in the background is holding the connection.

The software

I wrote the application using the Netbeans IDE. This IDE uses Mingw as a compiler for Windows. If you’re interessted in the code in can be download here including the servertool.exe file in the “server_tool\dist\Release\MinGW-Windows” directory.

The project can be loaded directly, but before the compiling works you have to add the following options in the linker options: -lws2_32 –liphlpapi -static-libgcc -static-libstdc++

The code is using the Windows winsock.dll, because this file got a lot of API’s to write some networking functionallity. The linker knows the application is using the winsock by linking the libraries with the options -lws2_32 –liphlpapi.

The linker options -static-libgcc -static-libstdc++   are needed to generate an executable with this library build into the executable. So basically it makes it possible to start the servertool.exe without any errors.

Proper linker options

 

The source code is not that much so it’s located all in 1 file, main.cpp

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

/* 
 * File:   main.cpp
 * Author: acer
 *
 * Created on 9 februari 2018, 14:09
 */

#include <stdio.h>
#include <stdlib.h>
#include <winsock2.h>
#include <iphlpapi.h>
#include <wchar.h> //for wcslen..

#pragma comment(lib,"ws2_32.lib") //Winsock Library
#pragma comment(lib,"Iphlpapi.lib")

#define FAIL 1
#define SUCCESS 0

int WSAinitialisatie();
int NameToIP();
int ClientTCPSocket(char *inet_address, int port_number);
int ClientUDPSocket(char *inet_address, int port_number);
int WhatToSend(int transportLayer, char ipAddress[], int portNum );
int Receiving();
int printMainMenu();
int startClientSession();
int getNetworkInfo();
int startTCPServer();
int getPortNumber();
int startUDPServer();
int initServer();

WSADATA wsa;
struct hostent *he;
struct in_addr **addr_list;
SOCKET s;
SOCKET new_socket;
struct sockaddr_in client;
struct sockaddr_in server;
struct sockaddr_in si_other;

char *message , server_reply[2000];
int recv_size;
char hostname[255];


/****************************************************************************
 main loop
****************************************************************************/
int main(int argc, char *argv[]) {
	
    int menuItem;
    int status;
 	
    if (WSAinitialisatie() == 0)
        printf("Initialised.\n");
    else{
        printf("Winsock.dll error\n");
    }
	
    while(1){
	
        menuItem = printMainMenu();
		
        switch (menuItem){
            case 1:
                getNetworkInfo();
		break;
                
            case 2:
                if (NameToIP() == SUCCESS)
                    printf("IP correctly resolved!\n");		
		break;
                
            case 3:
                if (startClientSession() == SUCCESS){
                    printf("Session correctly closed\n");
		}
		break;
                
            case 4:
                status = initServer();
		if (status == SUCCESS){
                    printf("Server closed\n");
                }
                else
                    printf("Number out of range (choose 1 or 2)\n");
                
                break;
                
            case 5:
            	printf("Use: netstat -p TCP -a -b in case running as administrator is not possible\n");
            	system("netstat -p TCP -a -b");
            	break;
            	
            case 6:
            	printf("Use: netstat -p TCP -a -b in case running as administrator is not possible\n");
            	system("netstat -p UDP -a -b");
            	break;
            	
            case 7:
                printf("Exit...\n");
		closesocket(s);
                return SUCCESS;
		break;
                
            default:
                closesocket(s);
                return 0;
                break;
        }
    }
    closesocket(s);
    WSACleanup();
    printf("Socket closed and winsock process closed.\n");
    return SUCCESS;
}

/****************************************************************************
 initServer(), initialize a server an starts the startTCPServer() or startUdpServer()
****************************************************************************/

int initServer(){
    char transpLyrSelected[10];
    int transpLyrCnvrt2Int;
    
    printf("Please enter transport layer:\n");
    printf("1. TCP\n");
    printf("2. UDP\n");
    fgets(transpLyrSelected,10,stdin);
    if (strlen(transpLyrSelected) > 2){
        printf("Error! to many chars\n");
        return FAIL;
    }
    
    if ((transpLyrSelected[0] > '2') || (transpLyrSelected[0] < '0') ){
        printf("choose a number (1 or 2)\n");
    }

    transpLyrCnvrt2Int = transpLyrSelected[0] - '0';
    if(transpLyrCnvrt2Int == 1){
        startTCPServer();
    }
    else if(transpLyrCnvrt2Int == 2){
        startUDPServer();
    }
    return SUCCESS;
}

/****************************************************************************
 startUDPServer(), start server for UDP packets
****************************************************************************/
int startUDPServer(){
    
    int slen , recv_len;
    char buf[1500];
    int receivePort;
    //struct sockaddr_in si_other;
    int iOptVal = 0;
    int iOptLen = sizeof (int);
    int iResult = 0;

    slen = sizeof(si_other);
	
    printf("Enter UDP port number: ");
    receivePort = getPortNumber();//convert char array to int
    printf("Entered port number is: %d\n", receivePort );
	//Create a socket
	//if((s = socket(AF_INET , SOCK_DGRAM , 0 )) == INVALID_SOCKET)
    if((s = socket(AF_INET , SOCK_DGRAM , 0 )) == INVALID_SOCKET)
    {
	printf("Could not create socket : %d" , WSAGetLastError());
    }
    printf("UDP Socket created.\n");
	
	//Prepare the sockaddr_in structure
    server.sin_family = AF_INET;
    server.sin_addr.s_addr = INADDR_ANY;
    server.sin_port = htons( receivePort );
    
	
	//Bind
    if( bind(s ,(struct sockaddr *)&server , sizeof(server)) == SOCKET_ERROR)
    {
	printf("Bind failed with error code : %d" , WSAGetLastError());
	return 1;
    }
    printf("Server is running, waiting for client...");

iResult = setsockopt(s, SOL_SOCKET, SO_BROADCAST, (char *) &iOptVal, iOptLen);
    if (iResult == SOCKET_ERROR)
        wprintf(L"getsockopt for SO_KEEPALIVE failed with error: %u\n", WSAGetLastError());

    //keep listening for data
    while(1){
        printf("Waiting for data...");
	memset(buf,'\0', 1500);//clear buffer
		
	//try to receive some data, this is a blocking call
	//if ((recv_len = recvfrom(s, buf, 1500, 0, (struct sockaddr *) &si_other, &slen)) == SOCKET_ERROR){
	if ((recv_len = recvfrom(s, buf, 1500, 0, (struct sockaddr *) &si_other, &slen)) == SOCKET_ERROR){
            printf("recvfrom() failed with error code : %d" , WSAGetLastError());
            return 1;
	}
	printf("Received packet from %s:%d\n", inet_ntoa(si_other.sin_addr), ntohs(si_other.sin_port));
	printf("Data: %s\n" , buf);
	if (buf[0] == 'q' && strlen(buf) < 3){ printf("Client send exit command. Exit...\n"); return 0; } //now reply the client with the same data if (sendto(s, buf, recv_len, 0, (struct sockaddr*) &si_other, slen) == SOCKET_ERROR){ printf("sendto() failed with error code : %d" , WSAGetLastError()); return 1; } } closesocket(s); WSACleanup(); return 0; } /**************************************************************************** getPortNumber(), gets a port number from the user ****************************************************************************/ int getPortNumber(){ char give_port[10]; int portNumber, lengthPortNumber; if(fgets(give_port, 10, stdin) != NULL){ if ((strlen(give_port)>0) && (give_port[strlen (give_port) - 1] == '\n'))
	        	give_port[strlen (give_port) - 1] = '\0';
        
        lengthPortNumber = strlen(give_port);
        if(lengthPortNumber > 5){
            printf("Number to big, max 5 digits\n");
            if(fgets(give_port, 10, stdin) == NULL){
                return FAIL;
            }
        }
        
        
        for(int i=0; i<lengthPortNumber; i++){ if ((give_port[i] > '9') || (give_port[i] < '0')){
                printf("Enter only numbers\n");
                return FAIL;
            }
        }
        portNumber = atoi (give_port);
    }
    else{
        return FAIL;
    }
    
    return portNumber;
} 
    
/****************************************************************************
 startTCPServer(), start server for TCP packets
****************************************************************************/
int startTCPServer(){
    int sizeCientStruct, i;
    int recPort;
    char replyChoise[1];
    char *portChoise;
    char messageSend[150];
    int slen;
    int receiveStatus;
    //struct sockaddr_in si_other;
    
    slen = sizeof(si_other);
    //Create a socket
    if((s = socket(AF_INET , SOCK_STREAM , 0 )) == INVALID_SOCKET)
    {
        printf("Could not create socket : %d" , WSAGetLastError());
        return FAIL;
    }
  
    printf("Enter port number: ");
    recPort = getPortNumber();
    if (recPort == FAIL){
        return FAIL;
    }
    
    //Prepare the sockaddr_in structure
    server.sin_family = AF_INET;
    server.sin_addr.s_addr = INADDR_ANY;
    server.sin_port = htons( recPort );
      
    //Bind
    if( bind(s ,(struct sockaddr *)&server , sizeof(server)) == SOCKET_ERROR)
    {
        printf("Bind failed with error code : %d" , WSAGetLastError());
        return FAIL;
    }
    printf("Socket ok, TCP server is running...\n");
    //Listen to incoming connections
    listen(s , 3);
    //Accept and incoming connection
    printf("Waiting for incoming connections...\n");
      
    sizeCientStruct = sizeof(struct sockaddr_in);
    new_socket = accept(s, (struct sockaddr *) &client, &sizeCientStruct);
    if (new_socket == INVALID_SOCKET)
    {
        printf("accept failed with error code : %d" , WSAGetLastError());
        return 1;
    }
    
    //initializing the messageSend buffer with 0
    for(i=0; i<150; i++){
    	messageSend[i] = 0;
    }
    
    printf("Connected\n");
    printf("1. automatic reply\n");
    printf("2. choose reply\n");
    fgets(replyChoise, 10, stdin);
    //printf("a, Waiting for message....\n");
    switch(replyChoise[0]){
  		
    case '1':
        printf("Waiting for data...(q is quit)");
  	while(1){
            //receiveStatus = recv_size = recvfrom(new_socket , server_reply , 2000 , 0, (struct sockaddr *) &si_other, &slen);
            if((recv_size = recvfrom(new_socket , server_reply , 2000 , 0, (struct sockaddr *) &si_other, &slen)) == SOCKET_ERROR){
                puts("recv failed");
                return FAIL;
            }
            else if (recv_size == 0){
                printf("The client closed the connection...bye\n");
                closesocket(s);
		return SUCCESS;
            }
            server_reply[recv_size] = '\0';
            
            printf("Received:\t %s\nWaiting for message... ", server_reply);
            if ((server_reply[0] == 'q') && (strlen(server_reply) <= 2) ){
		printf("The client closed the connection...bye\n");
                closesocket(s);
		return SUCCESS;
            }
            send(new_socket , server_reply , strlen(server_reply) , 0);
	}
        break;
    case '2':
        //printf("b, Waiting for message....\n");
    	while (1){
            printf("Waiting for message....");
            if((recv_size = recvfrom(new_socket , server_reply , 2000 , 0, (struct sockaddr *) &si_other, &slen)) == SOCKET_ERROR){
		printf("recv failed");
                return FAIL;
            }
            server_reply[recv_size] = '\0';
            //printf("\nReceived from %s:%d %s\n", inet_ntoa(si_other.sin_addr), ntohs(si_other.sin_port), server_reply);
            printf("\nReceived:\t\t %s", server_reply);
            if (server_reply[0] == 'q' && (strlen(server_reply) < 3) ){
		printf("Received exit form client...");
		closesocket(s);
		return SUCCESS;
            }
            printf("Send:\t\t\t ");
            fgets(messageSend, 150, stdin);
            //printf("d, Waiting for message....\n");
            if ((messageSend[0] == 'q') && (strlen(messageSend) <= 2)){ printf("Server closed the connection...\n"); closesocket(s); return SUCCESS; } send(new_socket , messageSend , strlen(messageSend) , 0); } break; default: break; } closesocket(s); } /**************************************************************************** getNetworkInfo(), collects all kind of computers network info ****************************************************************************/ int getNetworkInfo(){ IP_ADAPTER_INFO *pAdapterInfo; IP_ADAPTER_ADDRESSES *pAdapterAddresses; FIXED_INFO *pFixedInfo; IP_ADDR_STRING *pIPAddr; PIP_ADAPTER_ADDRESSES pCurrAddresses = NULL; char *bufferDescription; size_t lengteDescription; int cmpReturn; ULONG ulOutBufLen; ULONG ulOutBufLenAdapter; DWORD dwRetVal; ULONG flags = GAA_FLAG_INCLUDE_PREFIX; ULONG family = AF_UNSPEC; ULONG outBufLen = 0; ULONG Iterations = 0; UINT i; time_t leaseObtained; time_t leaseExpires; pFixedInfo = (FIXED_INFO *) malloc(sizeof (FIXED_INFO)); pAdapterInfo = (IP_ADAPTER_INFO *) malloc( sizeof(IP_ADAPTER_INFO) ); ulOutBufLen = sizeof (FIXED_INFO); ulOutBufLenAdapter = sizeof(IP_ADAPTER_INFO); outBufLen = sizeof(IP_ADAPTER_ADDRESSES); //Get the networkParams if (GetNetworkParams(pFixedInfo, &ulOutBufLen) == ERROR_BUFFER_OVERFLOW) { free(pFixedInfo); pFixedInfo = (FIXED_INFO *) malloc(ulOutBufLen); if (pFixedInfo == NULL) { printf("Error allocating memory needed to call GetNetworkParams\n"); } } if (dwRetVal = GetNetworkParams(pFixedInfo, &ulOutBufLen) != NO_ERROR) { printf("GetNetworkParams failed with error %d\n", dwRetVal); if (pFixedInfo) { free(pFixedInfo); } } //Get the adapterInfo if (GetAdaptersInfo( pAdapterInfo, &ulOutBufLenAdapter) != ERROR_SUCCESS) { free (pAdapterInfo); pAdapterInfo = (IP_ADAPTER_INFO *) malloc ( ulOutBufLenAdapter ); } if ((dwRetVal = GetAdaptersInfo( pAdapterInfo, &ulOutBufLenAdapter)) != ERROR_SUCCESS) { printf("GetAdaptersInfo call failed with %d\n", dwRetVal); } //Start printing the info printf("Host Name: \t%s\n", pFixedInfo->HostName);
if (strlen(pFixedInfo->DomainName) != 0){
    printf("\tDomain Name: %s\n", pFixedInfo->DomainName);
}

printf("Node Type: ");
switch (pFixedInfo->NodeType) {
case 1:
    printf("\t%s, best setting for small LAN\n", "Broadcast");
    break;
case 2:
    printf("\t%s check wins is active else other systems can't be find on LAN\n", "Peer to peer");
    break;
case 4:
    printf("\t%s\n", "Mixed");
    break;
case 8:
    printf("\t%s\n", "Hybrid");
    break;
default:
    printf("\n");
}
        
printf("DNS Servers:\n");
printf("\t\t%s\n", pFixedInfo->DnsServerList.IpAddress.String);

pIPAddr = pFixedInfo->DnsServerList.Next;
while (pIPAddr) {
    printf("\t\t%s\n", pIPAddr->IpAddress.String);
    pIPAddr = pIPAddr->Next;
}



if (strlen(pFixedInfo->ScopeId) != 0){
    printf("***********************\n");
    printf("\tNetBIOS Scope ID: %s\n", pFixedInfo->ScopeId);
    printf("HUGE ERROR! This option is from the winNT netBIOS stone age\n");
    printf("Remove this in WINS config tab in TCP/IP properties\n");
    printf("***********************\n");
}


if (pFixedInfo->EnableRouting){
    printf("***********************\n");
    printf("\tIP Routing Enabled: YES\n");
    printf("Possible 2 NICS and therefor routing enabled\n");
    printf("Use route print command for more info\n");
    printf("DISABLE at HKEY_LOCAL_MACHINE SYSTEM CurrentControlSet  Services Tcpip Parameters IPEnableRouter\n");
    printf("***********************\n");
    
}
//else
//    printf("\tIP Routing Enabled: No\n");

if (pFixedInfo->EnableProxy){
    printf("***********************\n");
    printf("\tWINS Proxy Enabled: YES\n");
    printf("Error possible Internet connection sharing (ICS) used\n");
    printf("if not? disable WINS Proxy\n");
    printf("HKEY_LOCAL_MACHINE SYSTEM CurrentControlSet Services NetBT Parameters EnableProxy\n");
    printf("***********************\n");
}

if (pFixedInfo->EnableDns){
    printf("***********************\n");
    printf("\tNetBIOS Resolution Uses DNS: Yes\n");
    printf("NetBIOS still used...Disable at WINS tab in TCP/IP settings.\n");
    printf("check also LMHOST file\n");
    printf("***********************\n");
}


//Get adapterAdresses
do {
    pAdapterAddresses = (IP_ADAPTER_ADDRESSES *) malloc(outBufLen);
    if (pAdapterAddresses == NULL) {
        printf
            ("Memory allocation failed for IP_ADAPTER_ADDRESSES struct\n");
        exit(1);
    }
    dwRetVal = GetAdaptersAddresses(family, flags, NULL, pAdapterAddresses, &outBufLen);
    if (dwRetVal == ERROR_BUFFER_OVERFLOW) {
        free(pAdapterAddresses);
        pAdapterAddresses = NULL;
    } else {
        break;
    }
    Iterations++;
} while ((dwRetVal == ERROR_BUFFER_OVERFLOW) && (Iterations < 3)); PIP_ADAPTER_INFO pAdapter = pAdapterInfo; printf("\n"); //next chapter after DNS info while (pAdapter) { pCurrAddresses = pAdapterAddresses; while (pCurrAddresses) { lengteDescription = wcslen(pCurrAddresses->Description);
        bufferDescription = (char *) malloc((lengteDescription+1) * sizeof(char));
        if (bufferDescription == NULL){
            printf("We are fucked!\n");
        }
        WideCharToMultiByte(CP_ACP, WC_COMPOSITECHECK, pCurrAddresses->Description, lengteDescription, bufferDescription, lengteDescription, NULL, NULL);
        bufferDescription[lengteDescription] = 0;
        cmpReturn = strcmp(bufferDescription, pAdapter->Description);
        if (cmpReturn == 0){
            if (wcslen(pCurrAddresses->DnsSuffix) != 0){
                printf("DNS Suffix:\t%S\n", pCurrAddresses->DnsSuffix);
            }
            printf("Friendly name:\t%S\n", pCurrAddresses->FriendlyName);
            if(pCurrAddresses->OperStatus == 1){
                
                //system("COLOR 2");
                printf("Status:\t\tUP!\n");
            }
            else
                printf("Status:\t\tDOWN\n");
          
            
        }
    pCurrAddresses = pCurrAddresses->Next;
    free(bufferDescription);
    }
    
    printf("Adapter name: \t%s\n", pAdapter->Description);
    printf("Adapter Addr: \t");
    for (i = 0; i < pAdapter->AddressLength; i++) {
        if (i == (pAdapter->AddressLength - 1))
            printf("%.2X\n",(int)pAdapter->Address[i]);
        else
            printf("%.2X-",(int)pAdapter->Address[i]);
    }
    printf("IP Address: \t%s\n", pAdapter->IpAddressList.IpAddress.String);
    printf("IP Mask: \t%s\n", pAdapter->IpAddressList.IpMask.String);
    printf("Gateway: \t%s\n", pAdapter->GatewayList.IpAddress.String);
    
    if (pAdapter->DhcpEnabled) {
        
        if(strlen(pAdapter->DhcpServer.IpAddress.String) != 0){
            printf("DHCP Server: \t%s\n", pAdapter->DhcpServer.IpAddress.String);
            leaseObtained = pAdapter->LeaseObtained;
            leaseExpires = pAdapter->LeaseExpires;
            printf("Lease from:\t%s", ctime(&leaseObtained));
            printf("Lease till:\t%s", ctime(&leaseExpires));
        }
        else
           printf("\t\tDHCP ENABLED\n");
    }
    else
        printf("\tDHCP DISABLED\n");
	
    pAdapter = pAdapter->Next;
    printf("\t***\n");
}


        
if (pAdapterInfo)
    free(pAdapterInfo);
if (pFixedInfo) {
    free(pFixedInfo);
    pFixedInfo = NULL;
}
    
    
    
}

/****************************************************************************
 startClientSession(), initialize a session followed by ClientTCPSocket() of ClientUDPSocket
****************************************************************************/
int startClientSession(){
	
	int n;
	char give_ip[50];
	char giveSocketType[10];
	int portNumber;
	int stopSending = 0;
        int socketSelected;
	
	printf("Enter IP (1 for default 127.0.0.1):\n");
	fgets(give_ip, 50, stdin);
	n = strlen(give_ip);
	if (n < 2){ printf("ERROR To less chars quiting...\n"); return FAIL; } if ((strlen(give_ip)>0) && (give_ip[strlen (give_ip) - 1] == '\n'))
	        	give_ip[strlen (give_ip) - 1] = '\0';
	if ((give_ip[0] == '1') && (n < 3)){ strcpy(give_ip, "127.0.0.1"); } printf("\nEnter a port number: \n"); portNumber = getPortNumber(); if(portNumber == FAIL){ return FAIL; } printf("\nPlease choose type of socket to create:\n"); printf("1, TCP\n"); printf("2. UDP\n"); fgets(giveSocketType, 10, stdin); if ((strlen(giveSocketType)>0) &&
                (giveSocketType[strlen (giveSocketType) - 1] == '\n'))
                    giveSocketType[strlen (giveSocketType) - 1] = '\0';
	n = strlen(giveSocketType);
	if (n > 1){
            printf("Use only 1 digit, choose a number (1 or 2)\n");
            return FAIL;
        }
		
        if ((giveSocketType[0] > '2') || (giveSocketType[0] < '0') ){ printf("choose a number (1 or 2)\n"); return FAIL; } socketSelected = giveSocketType[0] - '0'; if(socketSelected == 1){ if (ClientTCPSocket(give_ip, portNumber) == 0){ printf("TCP Socket OK! with IP %s and port %d\n", give_ip, portNumber); } else{ printf("\nFailed to create socket, please check ip and port %s:%d\n", give_ip, portNumber); return FAIL; } } else if(socketSelected == 2){ if (ClientUDPSocket(give_ip, portNumber) == 0){ printf("UDP Socket OK! with IP %s and port %d\n", give_ip, portNumber); } else{ printf("\nFailed to create socket, please check ip and port %s:%d\n", give_ip, portNumber); return FAIL; } } WhatToSend(socketSelected, give_ip, portNumber); } /**************************************************************************** printMainMenu(), displays the main menu interface ****************************************************************************/ int printMainMenu(){ char inputMenu[10]; int itemSelected; int inputLength; do { printf("***********************************************\n"); printf("1. Get network information\n"); printf("2. Resolve hostname to IP (DNS check)\n"); printf("3. Client connect socket (Firewall test TX)\n"); printf("4. Server connect socket (Firewall test RX)\n"); printf("5. List services occupying TCP ports\n"); printf("6. List services occupying UDP ports\n"); printf("7. Exit\n"); printf("***********************************************\n"); fgets(inputMenu, 10, stdin); inputLength = strlen(inputMenu); }while(inputLength == 1); if (inputLength > 2)
		printf("Number to big, use only 1 digit\n");
        
        if(inputMenu[0] > '8' || inputMenu[0] < '1'){ printf("Number out of range.\n"); } if ((strlen(inputMenu)>0) && (inputMenu[strlen (inputMenu) - 1] == '\n'))
	        	inputMenu[strlen (inputMenu) - 1] = '\0';
	
	itemSelected = inputMenu[0] - '0';
	return itemSelected;
}

/****************************************************************************
 Receiving(), used to receive data from a server. Used for client mode
****************************************************************************/
int Receiving(){
	int i;
	
	for(i=0; i<2000; i++){//empty buffer for just in case
		server_reply[i] = 0;
	}
	
	if((recv_size = recv(s , server_reply , 2000 , 0)) == SOCKET_ERROR)
	{
		printf("recv failed");
		return 1;
	}
	
	printf("Reply received:");
	//Add a NULL terminating character to make it a proper string before printing
	server_reply[recv_size] = '\0';
	printf("%s\n", server_reply);
	if ((server_reply[0] == 'q') && (strlen(server_reply) < 3 )){ return 2; //2 means quit has send by server } return 0; } /**************************************************************************** WhatToSend(), some options to send predefined data ****************************************************************************/ int WhatToSend(int transportLayer, char ipAddress[], int portNum ){ char a[10]; int n; int itemSelected; char your_message[200]; //struct sockaddr_in si_other; int slen=sizeof(si_other); char buf[1500]; if(transportLayer == 1){ printf("Please select what to send?\n"); printf("1. GET / HTTP/1.1\\r\\n\\r\\n\n"); printf("2. Send a written message\n"); printf("3. Stop sending\n"); fgets(a,10,stdin); if (strlen(a) > 2){
		printf("ERROR, To many chars.\n");
		return FAIL;
	}
	
	itemSelected = a[0] - '0';
	printf("De itemSelected is: %d\n", itemSelected);
	switch (itemSelected){
		
            case 1:
		message = "GET / HTTP/1.1\r\n\r\n";
		if( send(s , message , strlen(message) , 0) < 0)
		{
                    printf("Send failed");
                    return FAIL;
		}
		Receiving();
		break;
            case 2:
			//while ((your_message[0] != 'q') && (strlen(your_message) <= 2)){ while (1){ printf("\nPlease write a message (q to quit): "); fgets(your_message, 200, stdin); n = strlen(your_message); if ((strlen(your_message)>0) && (your_message[strlen (your_message) - 1] == '\n'))
	   	    	your_message[strlen (your_message) - 1] = '\0';
	   	    
                                
                    if( send(s , your_message , n , 0) < 0)
                    {	
			printf("Send failed");
			return FAIL;
                    }
                    if (Receiving() == 2){
			printf("Server closed the connection...bye\n");
			return SUCCESS;
                    }
                    if(your_message[0] == 'q' && n<3){
                        return SUCCESS;
                    }	
		}
			
                    break;
		case 3:
                    printf("Stopped sending\n");
                    closesocket(s);
                    return 2;
                    break;
		default:
                    printf("Stopped sending\n");
                    closesocket(s);
                    return 2;
                    break;	
		
	}
    }	
    else if (transportLayer == 2){

        while(1){
    
            printf("\nPlease write a message (q to quit): ");
            fgets(your_message, 200, stdin);
            printf("send:\t%s\n", your_message);	
            //send the message
            if (sendto(s, your_message, strlen(your_message) , 0 , (struct sockaddr *) &si_other, slen) == SOCKET_ERROR){
		printf("sendto() failed with error code : %d" , WSAGetLastError());
		return FAIL;
            }
            if (your_message[0] == 'q')
                return SUCCESS;
            memset(buf,'\0', 1500);
            //try to receive some data, this is a blocking call
            if (recvfrom(s, buf, 1500, 0, (struct sockaddr *) &si_other, &slen) == SOCKET_ERROR){
		printf("recvfrom() failed with error code : %d" , WSAGetLastError());
		return FAIL;
            }
	
            printf("%s", buf);
        }
    
    }	
	
    return SUCCESS;
}

/****************************************************************************
 ClientTCPSocket(), build the TCP socket
****************************************************************************/
int ClientTCPSocket(char *inet_address, int port_number){
	
    if((s = socket(AF_INET , SOCK_STREAM , 0 )) == INVALID_SOCKET){
        printf("Could not create socket : %d" , WSAGetLastError());
    }
	
    server.sin_addr.s_addr = inet_addr(inet_address);//"212.61.147.8"
    server.sin_family = AF_INET;
    server.sin_port = htons( port_number );//80
	//Connect to remote server
    if (connect(s , (struct sockaddr *)&server , sizeof(server)) < 0){ printf("connect error %s %ui", inet_address, port_number); return 1; } printf("Connected to IP %s:%d\n",inet_address, port_number); return SUCCESS; } /**************************************************************************** ClientUDPSocket(), build the UDP socket ****************************************************************************/ int ClientUDPSocket(char *inet_address, int port_number){ //Create a socket if((s = socket(AF_INET , SOCK_DGRAM, IPPROTO_UDP )) == INVALID_SOCKET){ printf("Could not create socket : %d" , WSAGetLastError()); } //server.sin_addr.s_addr = inet_addr(inet_address);//"212.61.147.8" si_other.sin_addr.S_un.S_addr = inet_addr(inet_address);//"212.61.147.8" si_other.sin_family = AF_INET; si_other.sin_port = htons( port_number );//80 //Connect to remote server //printf("Ready to transmit UDP on IP %s and port %d\n",inet_address, port_number); return 0; } /**************************************************************************** NameToIP(), resolve ip from name. Usefull to analyze the http1.1 protocol ****************************************************************************/ int NameToIP(){ char ip[100]; int i = 0; printf("Give a hostname to get the IP address\n"); fgets(hostname, 255, stdin); if ((strlen(hostname)>0) && (hostname[strlen (hostname) - 1] == '\n'))
       	hostname[strlen (hostname) - 1] = '\0';
	
    printf("\nHostname %s ", hostname);
    if ( (he = gethostbyname( hostname ) ) == NULL){
	printf("gethostbyname failed : %d" , WSAGetLastError());
	return 1;
    }
	
    //Cast the h_addr_list to in_addr , since h_addr_list also has the ip address in long format only
    addr_list = (struct in_addr **) he->h_addr_list;
	
    for(i = 0; addr_list[i] != NULL; i++) {
        strcpy(ip , inet_ntoa(*addr_list[i]) );
    }
    //DeIP = ip;
    printf("is resolved to : %s\n\n" , ip);
    return 0;
}

/****************************************************************************
 WSAinitialisatie(), winsock.dll needs to be initialized
****************************************************************************/
int WSAinitialisatie(){
	
    printf("\nInitialising Winsock...\n");
    if (WSAStartup(MAKEWORD(2,2),&wsa) != 0){
        printf("Failed. Error Code : %d",WSAGetLastError());
	return FAIL;
    }
    return SUCCESS;
}






 

I hope you can use this code for your own projects and thanks for reading!