Client/Server (Windows) with C Sockets

Asked

Viewed 5,046 times

6

I’m trying to write a program written in C, which is able to upload a file or text to a particular server.

I searched a lot on google but most of the tutorials are aimed at linux environment, either not so complete or offer code ready without any explanation.

I have some notion of C, but the sockets part is a salad and charges the use of various chained procedures. I need to understand only this matter of sockets and communication between client/server.

  • 2

    Recommendation requests do not usually work well here on the site (generate many responses and it is difficult/subjective to judge which would be the best). So I removed that part of the question. Let’s see if someone can explain the path of the stones to you right here, using external links only for reference/complementation of the explanation.

  • One more thing: if possible, edit the question including details about your attempts. If people understand more precisely where their difficulty is, they are more likely to get a good answer.

  • Friend, even if you are from the C area, I recommend using C++ and Boost.Asio

  • Specify the server type. Alternatives are Winhttp and FTP with reference: http://msdn.microsoft.com/en-us/library/ms905225.aspx

1 answer

9


You should read the MSDN: Winsock 2

There you find the tutorials Using Winsock (I recommend using C++ for these Microsoft Apis)

There’s this tutorial from my friend Felix_poison: Click Here (This tutorial is specifically in C)

And now follows a sample client and server code from Winsockets.

Server:

/*
 * Servidor com WinSock 2
 * 
 * Autor: Ighor Augusto Barreto Candido
 *
 * NOTA: compilado com cl.exe (compilador do Visual Studio)
 */

#undef UNICODE

#define WIN32_LEAN_AND_MEAN

#include <windows.h>
#include <winsock2.h>
#include <ws2tcpip.h>
#include <stdlib.h>
#include <stdio.h>

// Need to link with Ws2_32.lib
#pragma comment (lib, "Ws2_32.lib")
// #pragma comment (lib, "Mswsock.lib")

#define DEFAULT_BUFLEN 512
#define DEFAULT_PORT "27015"

int __cdecl main(void) 
{
    WSADATA wsaData;
    int iResult;

    SOCKET ListenSocket = INVALID_SOCKET;
    SOCKET ClientSocket = INVALID_SOCKET;

    struct addrinfo *result = NULL;
    struct addrinfo hints;

    int iSendResult;
    char recvbuf[DEFAULT_BUFLEN];
    int recvbuflen = DEFAULT_BUFLEN;

    printf("\n\n\t\t\t\t\t Socket TCP/IP Server by Ighor Augusto\n");
    printf("\n\t-> Inicializando a biblioteca de Winsock...");  
    // Inicializando a biblioteca de Winsock
    iResult = WSAStartup(MAKEWORD(2,2), &wsaData);
    if (iResult != 0) {
        printf("\t\t[-] WSASturtup falhou! Erro: %d\n\n", iResult);
        return 1;
    }
    printf("\t\t[+] Biblioteca inicializada com sucesso!\n");

    ZeroMemory(&hints, sizeof(hints));
    hints.ai_family = AF_INET;
    hints.ai_socktype = SOCK_STREAM;
    hints.ai_protocol = IPPROTO_TCP;
    hints.ai_flags = AI_PASSIVE;

    printf("\t-> Resolvendo endereco e porta do servidor...");
    // Resolvendo o endereco e porta do servidor
    iResult = getaddrinfo(NULL, DEFAULT_PORT, &hints, &result);
    if ( iResult != 0 ) {
        printf("getaddrinfo failed with error: %d\n", iResult);
        WSACleanup();
        return 1;
    }printf("\t\t[+] Sucesso!\n");


    printf("\t-> Criando SOCKET para conexao...");
    // Criando Socket
    ListenSocket = socket(result->ai_family, result->ai_socktype, result->ai_protocol);
    if (ListenSocket == INVALID_SOCKET) {
        printf("\t\t\t[-] Socket falhou! Erro: %ld\n\n", WSAGetLastError());
        freeaddrinfo(result);
        WSACleanup();
        return 1;
    }
    printf("\t\t\t[+] Socket criado com sucesso!\n");       

    printf("\t-> Setando TCP listening socket...\n\n");
    printf("\t-> bind()...");
    // Setup TCP listening socket
    iResult = bind( ListenSocket, result->ai_addr, (int)result->ai_addrlen);
    if (iResult == SOCKET_ERROR) {
            printf("\t\t\t\t\t\t[-] bind() falhou! Erro: %d\n\n", WSAGetLastError());
            freeaddrinfo(result);
            closesocket(ListenSocket);
            WSACleanup();
            return 1;
    }
    printf("\t\t\t\t\t\t[+] Sucesso!\n");

    freeaddrinfo(result);

    printf("\t-> listen()...");
    iResult = listen(ListenSocket, SOMAXCONN);
    if (iResult == SOCKET_ERROR) {
            printf("\t\t\t\t\t\t[-] listen() falhou! Erro: %d\n\n", WSAGetLastError());
            closesocket(ListenSocket);
            WSACleanup();
            return 1;
    }
    printf("\t\t\t\t\t\t[+] Sucesso!\n");

    printf("\t-> Aguardando conexoes! accept()...");
    // Aceitando um cliente socket
    ClientSocket = accept(ListenSocket, NULL, NULL);
    if (ClientSocket == INVALID_SOCKET) {
            printf("\t\t\t[-] accept() falhou! Erro: %d\n\n", WSAGetLastError());
            closesocket(ListenSocket);
            WSACleanup();
            return 1;
    }
    printf("\t\t\t[+] Sucesso!\n");

    closesocket(ListenSocket);

    printf("\n\t[+] Servidor pronto para receber dados!!!\n\n");
    // Recebe ate o cliente encerrar a conexao
    do {

        printf("\t-> Aguardando...");
        iResult = recv(ClientSocket, recvbuf, recvbuflen, 0);
        if (iResult > 0) {
            printf("\t\t\t\t\t[+] Bytes recebidos: %d\n", iResult);
            printf("\t-> Enviando um eco ao cliente...");
            // Echo the buffer back to the sender
            iSendResult = send( ClientSocket, recvbuf, iResult, 0 );
            if (iSendResult == SOCKET_ERROR) {
                printf("\t\t\t[-] send() falhou! Erro: %d\n", WSAGetLastError());
                closesocket(ClientSocket);
                WSACleanup();
                return 1;
            }
            printf("\t\t\t[+] Sucesso! Bytes enviados: %d\n", iSendResult);
        }
        else if (iResult == 0)
            printf("\t\t\t\t\t[-] Conexao fexada pelo cliente!\n");
        else  {
            printf("\t\t\t\t\t[-] recv() falhou! Erro: %d\n", WSAGetLastError());
            closesocket(ClientSocket);
            WSACleanup();
            return 1;
        }

    } while (iResult > 0);

    printf("\t-> Encerrando...");
    // Fexando a conexao quando terminarmos
    iResult = shutdown(ClientSocket, SD_SEND);
    if (iResult == SOCKET_ERROR) {
            printf("\t\t\t\t\t[-] shutdown() falhou! Erro: %d\n", WSAGetLastError());
            closesocket(ClientSocket);
            WSACleanup();
            return 1;
    }
    printf("\t\t\t\t\t[+] Encerrado!\n");
    printf("\n\n\t### Bye!!! ###\n");
    // cleanup
    closesocket(ClientSocket);
    WSACleanup();

    return 0;

}

Client:

/*
 * Cliente com Winsock 2
 *
 * Autor: Ighor Augusto Barreto Candido
 *
 * NOTA: compilado com cl.exe (compilador do Visual Studio)
 */

 #ifndef WIN32_LEAN_AND_MEAN
 #define WIN32_LEAN_AND_MEAN
 #endif

#include <windows.h>
#include <winsock2.h>
#include <ws2tcpip.h>
#include <stdlib.h>
#include <stdio.h>


// Ws2_32.lib, Mswsock.lib, and Advapi32.lib
#pragma comment (lib, "Ws2_32.lib")
#pragma comment (lib, "Mswsock.lib")
#pragma comment (lib, "AdvApi32.lib")

#define DEFAULT_BUFLEN 512
#define DEFAULT_PORT "27015"

int __cdecl main(int argc, char **argv) 
{
   WSADATA wsaData;
   SOCKET ConnectSocket = INVALID_SOCKET;
   struct addrinfo *result = NULL,
                *ptr = NULL,
                hints;
   char *sendbuf = "this is a test";
   char recvbuf[DEFAULT_BUFLEN];
   int iResult;
   int recvbuflen = DEFAULT_BUFLEN;

// Usage
if (argc != 2) {
    printf("\n\n\t\tCliente Socket TCP/IP by Ighor Augusto\n");
    printf("\t\tUsage: %s endereco do host\n", argv[0]);
    return 1;
}

printf("\n\n\t\t\t\t\t Socket TCP/IP Server by Ighor Augusto\n");
printf("\n\t-> Inicializando a biblioteca de Winsock...");
// Initializando a biblioteca de Winsock
iResult = WSAStartup(MAKEWORD(2,2), &wsaData);
if (iResult != 0) {
    printf("\t\t[-] WSASturtup falhou! Erro: %d\n\n", iResult);
    return 1;
}
printf("\t\t[+] Biblioteca inicializada com sucesso!\n");

ZeroMemory( &hints, sizeof(hints) );
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
hints.ai_protocol = IPPROTO_TCP;

printf("\t-> Resolvendo endereco e porta do servidor...");
// Resolvendo o endereco e porta do servidor
iResult = getaddrinfo(argv[1], DEFAULT_PORT, &hints, &result);
if ( iResult != 0 ) {
    printf("\t\t[-] getaddrinfo() falhou! Erro: %d\n\n", iResult);
    WSACleanup();
    return 1;
}
printf("\t\t[+] Sucesso!\n");

printf("\t-> Iniciando procedimento de conexao...");
// Lanca tentativas de conexao com o host até obter sucesso... ou nao.
for(ptr=result; ptr != NULL ;ptr=ptr->ai_next) {

    printf("\n\t-> Criando SOCKET para conexao...");
    // Criando socket
    ConnectSocket = socket(ptr->ai_family, ptr->ai_socktype, 
        ptr->ai_protocol);
    if (ConnectSocket == INVALID_SOCKET) {
        printf("\t\t\t\t[-] Socket falhou! Erro: %ld\n\n", WSAGetLastError());
        WSACleanup();
        return 1;
    }
    printf("\t\t\t[+] Socket criado com sucesso!\n");

    printf("\t-> Conectando ao host...");
    // Connect to server.
    iResult = connect( ConnectSocket, ptr->ai_addr, (int)ptr->ai_addrlen);
    if (iResult == SOCKET_ERROR) {
        closesocket(ConnectSocket);
        ConnectSocket = INVALID_SOCKET;
        continue;
    }
    break;
}

freeaddrinfo(result);

if (ConnectSocket == INVALID_SOCKET) {
    printf("\t\t\t\t[-] Conexao com o server invalida!\n\n");
    WSACleanup();
    return 1;
}
printf("\t\t\t\t[+] Sucesso!!!\n");

printf("\t-> Enviando buffer inicial...");
// Enviando um buffer inicial
iResult = send( ConnectSocket, sendbuf, (int)strlen(sendbuf), 0 );
if (iResult == SOCKET_ERROR) {
    printf("\t\t\t\t[-] send() falhou! Erro: %d\n\n", WSAGetLastError());
    closesocket(ConnectSocket);
    WSACleanup();
    return 1;
}
printf("\t\t\t\t[+] Sucesso! Bytes enviados: %ld\n", iResult);

printf("\t-> Encerrando conexao...");
// Encerrando conexao desde que nao iremos enviar mais buffers
iResult = shutdown(ConnectSocket, SD_SEND);
if (iResult == SOCKET_ERROR) {
    printf("\t\t\t\t[-] shutdown() falhou! Erro: %d\n", WSAGetLastError());
    closesocket(ConnectSocket);
    WSACleanup();
    return 1;
}
printf("\t\t\t\t[+] Encerrado!\n");

printf("\t-> Lendo a resposta do servidor...");
// Aguardando resposta do servidor
do {
    iResult = recv(ConnectSocket, recvbuf, recvbuflen, 0);
    if ( iResult > 0 ) 
        printf("\t\t\t[+] Sucesso! Bytes recebidos: %d\n", iResult);
    else if ( iResult == 0 )
        printf("\n\t[+] Procedimento finalizado!\n");
    else
        printf("\t\t\t[-] recv() falhou! Erro: %d\n", WSAGetLastError());

} while( iResult > 0 );

printf("\n\n\t### Bye!!! ###\n");
// cleanup
closesocket(ConnectSocket);
WSACleanup();

return 0;
}

I hope I’ve helped!!!

Hug!

  • Thank you, the tutorial helped me a lot!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.