post
poster: enc
description: first socket program
language: C++
[download]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
// stream socket INET
// Practice of using sockets 


#include<winsock.h>
#include<string>
#include<stdio.h>
using namespace std;
#pragma comment(lib,"ws2_32.lib") // <--only works in vs but its fast :D
#define SCK_VERSION2        0x0202 // this is using the latest version of winsock

bool ConnectToHost(int portNum, WSADATA &wsadata,SOCKET s)
    {   
        // notice we are using version 2 here 
        int error = WSAStartup(0x0202,&wsadata);
    
        //check wsaStartup 
         if(error)
         {
             printf("error starting up ");
             return false;
         }

         //Are we not using the new version of winsock?

     if(wsadata.wVersion != 0x0202)
     {
         WSACleanup();
         printf("failed to use winsock version 2!"); 
         return false;
    

     }

      // necessary standard info for a basic socket

     SOCKADDR_IN target; //socket address information

     target.sin_family = AF_INET; //AF NET == net address type
     target.sin_port = htons(80); // the port research htons  //(PortNum)
     target.sin_addr.s_addr = inet_addr("209.40.204.162"); // the target address //IPAddress


     // this is actually creating the socket
     s = socket(AF_INET,SOCK_STREAM, IPPROTO_TCP);

     if(s== INVALID_SOCKET) //Bool identifier for socket
     {
     printf("INVALID_SOCKET == true error creating sock"); 
     return false; // error on creating the socket

     }
      //Try connecting ...
     
     if(connect(s,(SOCKADDR     *) &target,sizeof(target))
         == SOCKET_ERROR)
     {
         

         printf("error connecting the socket to host"); 
         return false;  // error connecting
              
     }
    
     else 
     {
         return true; //good to go I bet sec lme see somthing 
     }

    } 
    //CLOSECONNECTION – shuts down the socket and closes any connection on it
void CloseConnection (SOCKET s)
{
    //Close the socket if it exists
    if (s)
        closesocket(s);

    WSACleanup(); //Clean up Winsock
}
int main()
{

//hostent *test;
//test = gethostbyname("209.40.204.162");

    SOCKET sock = INVALID_SOCKET; //this is the socket handle
    
    /* The code below is what we 
       us to connect to a host */
    WSADATA wsadata;  // o shit 
    

        bool win = ConnectToHost(0,wsadata,sock);
        if(!win)
        {
        CloseConnection(sock);
        printf("nogo\n");
        }
        else
        {
            printf(":D");
        }

        system("pause"); 
}