FRIHOST FORUMS SEARCH FAQ TOS BLOGS COMPETITIONS
You are invited to Log in or Register a free Frihost Account!

Useful winsock codes




Useful winsock codes Wink
Code:
#include <winsock2.h>
#include <windows.h>
#include <iostream>
#pragma comment(lib,"ws2_32.lib")

using namespace std;

int main (){
   WSADATA wsaData;

    if (WSAStartup(MAKEWORD(2,2), &wsaData) != 0) {
      cout << "WSAStartup failed.\n";
        system("pause");
      return 1;
    }

   SOCKET Socket=socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);

   struct hostent *host;
   host = gethostbyname("www.cplusplus.com");

   SOCKADDR_IN SockAddr;
   SockAddr.sin_port=htons(80);
   SockAddr.sin_family=AF_INET;
   SockAddr.sin_addr.s_addr = *((unsigned long*)host->h_addr);

   cout << "Connecting...\n";
   if(connect(Socket,(SOCKADDR*)(&SockAddr),sizeof(SockAddr)) != 0){
      cout << "Could not connect";
      system("pause");
      return 1;
   }
   cout << "Connected.\n";

   send(Socket,"GET / HTTP/1.1\r\nHost: www.cplusplus.com\r\nConnection: close\r\n\r\n", strlen("GET / HTTP/1.1\r\nHost: www.cplusplus.com\r\nConnection: close\r\n\r\n"),0);
   char buffer[10000];

   int nDataLength;

   while( (n = recv( socket, &buff, sizeof(buff), 0 ) ) > 0 )
   {
      cout << buffer;
   }

   }

   closesocket(Socket);
        WSACleanup();

   system("pause");
   return 0;
}




0 blog comments below




FRIHOST HOME | FAQ | TOS | ABOUT US | CONTACT US | SITE MAP
© 2005-2011 Frihost, forums powered by phpBB.