My name is Vasyl Khrystiuk‎ > ‎pub‎ > ‎cpp‎ > ‎

winsock2

Tags: cpp_tag

Changed source version from "Winsock для всех" http://club.shelek.ru/viewart.php?id=35
Also with some changes it can be used for implementing this: http://citforum.ru/internet/servers/glava3_1_3.shtml


#include <stdio.h>
#include "winsock2.h"
#include <iostream.h>
#include <conio.h>

#define request "trash" //query
#define MAX_PACKET_SIZE         65535

int main(int argc, char* argv[])
{
    WSADATA            ws;
    SOCKET            s;
    sockaddr_in        adr;
    hostent*        hn;
    char            buff [MAX_PACKET_SIZE];

    if (WSAStartup (0x0202, &ws) != 0){// init
        return -1;// Error
    }

    if(INVALID_SOCKET == (s = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP))){// create socket
        return -1;// Error
    }

    printf("Program made by modern_sky_angel\n");
    printf("%s ",argv[1]);
    
    if (NULL == ( hn = gethostbyname (argv[1]))){// get addres
        return -1;// Error
    }

    // fill fields for connect
    adr.sin_family                = AF_INET;
    adr.sin_addr.S_un.S_addr    = *(DWORD* ) hn->h_addr_list[0];
    adr.sin_port                = htons (445);

    if (SOCKET_ERROR == connect(s,(sockaddr*)&adr, sizeof(adr))){// create connection
        int res = WSAGetLastError();// Error
        return -1;
    }

    while (true){// send request to server
        if (SOCKET_ERROR == send (s, &request, sizeof(request), 0) ){
                int res = WSAGetLastError ();
                return -1; // Error
        }
    }

    int len = 0;
    do{
        if (SOCKET_ERROR == (len = recv (s, (char *) &buff, MAX_PACKET_SIZE, 0))){
            int res = WSAGetLastError ();
            return -1;
        }
        for (int i = 0; i<len; i++) printf("%c", buff [i]);
    }while (len!=0); //get data by parts while len != 0.

    if (SOCKET_ERROR == closesocket(s)){// close connection
        return -1;// Error
    }
    return 0;
}


Comments