Socket connection

I want a simple socket code that looks like this.
SendData(hostname,port,data,size_t data)
GetData(hostname,port,&data,size_t &data)

I want to send a request to localhost on a set port and then save the information they send me back, how do I do this?
Last edited on
Sorry but that didn't help me at ALL!
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
Linking...
win_tcpsocket.obj : error LNK2001: unresolved external symbol _WSAStartup@8
win_tcpsocket.obj : error LNK2001: unresolved external symbol _WSACleanup@0
win_tcpsocket.obj : error LNK2001: unresolved external symbol _socket@12
win_tcpsocket.obj : error LNK2001: unresolved external symbol _WSAGetLastError@0
win_tcpsocket.obj : error LNK2001: unresolved external symbol _connect@12
win_tcpsocket.obj : error LNK2001: unresolved external symbol _htons@4
win_tcpsocket.obj : error LNK2001: unresolved external symbol _inet_addr@4
win_tcpsocket.obj : error LNK2001: unresolved external symbol _gethostbyname@4
win_tcpsocket.obj : error LNK2001: unresolved external symbol _bind@12
win_tcpsocket.obj : error LNK2001: unresolved external symbol _accept@12
win_tcpsocket.obj : error LNK2001: unresolved external symbol _listen@8
win_tcpsocket.obj : error LNK2001: unresolved external symbol _send@16
win_tcpsocket.obj : error LNK2001: unresolved external symbol _recv@16
win_tcpsocket.obj : error LNK2001: unresolved external symbol _shutdown@8
win_tcpsocket.obj : error LNK2001: unresolved external symbol _closesocket@4
LIBCD.lib(wincrt0.obj) : error LNK2001: unresolved external symbol _WinMain@16


Please, please, please read the name I just want this simple as possible.
1
2
3
4
5
string str, str2;

SocketConnect("127.0.0.1",1500);
SendData(str);
ReceiveData(str2);


When I open the connection and then send a specific set of data, the server will send me back a response with data that's needed. That's all I need, I don't know how I'm having such a hard damn time with it >:{
Last edited on
You have to link the winsock library. It depends on your compiler how you link stuff like that.
MSDN has an example exactly as you describe it (except from the saving part)
http://msdn.microsoft.com/en-us/library/ms738545(VS.85).aspx

You can save the data received in a file... They are in the received buffer.
THIS IS DRIVING ME FRIEKEN CRAZY!! Whenever I even include <winsock2.h> I get like 400 errors!! I'm using Visual C++ 6.0 - I don't know if I need to upgrade something but this is just driving me crazy, the only thing I can include and it will actually compile is <winsock.h> in which case NONE of these examples work. In fact I took the full source example from MSDN and got so many errors I wasn't even going to BEGIN to work through them. I know people hate to do this but can I please just get a short source to work off that includes <winsock.h> and actually compiles, because I'm going crazy trying to figure this crap out!!
Did you link the winsock library? In order to link it, I did this:

Project -> Current Properties -> Configuration Properties -> Linker
-> Additional Library Directories

Add ws2_32.lib

There might be more, but this what I remember doing.
Yes I added it. As far as I know you need to create a new socket, connect to a specific IP and port, send and/or receive data through the connected sockets IP/Port, and finally do a WSACleanup/Socket disconnect. Now I just need an EXTREMELY simple code that does something like this.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#define SOCKIP 127.0.0.1
#define SOCKPORT 5000

SOCKET sock;

char *Message = "Hello world!";
char Message2 [4028] = {0};

sock.CreateNew(SocketOne);
sock.Connect(SocketOne,SOCKIP,SOCKPORT);
sock.SendData(SocketOne,Message,sizeof(Message));
sock.ReceiveData(SocketOne,&Message2,sizeof(Message2));
sock.Close(SocketOne);
sock.WSACleanup;


Basically I retrieve a message through a separate code which I already have working. This message is then sent to an exe I made and the exe will sent a message back based on the message you sent it. This is just a test for me to learn socket connections and I can't figure it out.

I just need a SIMPLE framework that creates a new socket, connects to that socket through 127.0.0.1:5000, sends the data that the previous function I made retrieves (I can edit this myself obviously), then when the exe sends you a message back then record it and output it to the window. BAM! That's all I need done, if you can help me then I'll cut out my heart and mail it to you because that's how much I'll love you!
Last edited on
This is mostly from the microsofts example above with some modifications to display the results:

SERVER:
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
110
111
112
113
114
115
116
117
118
119
120
// Need to link with Ws2_32.lib, Mswsock.lib, and Advapi32.lib
#include <iostream>
#include <Winsock2.h>
#include <Ws2tcpip.h>
#include <string>
const char* DEFAULT_PORT = "27015";
const int DEFAULT_BUFLEN = 512;

int main(){
   WSADATA wsaData;
   int iResult;

   //Initialize Winsock
   std::cout << "Calling socket dll.\n";
   iResult = WSAStartup( MAKEWORD( 2, 2 ), &wsaData );
   if ( iResult != 0 ){
      std::cout << "Error on starting up Socket.\nError code: " << iResult << std::endl;
      return 1;
   }

   struct addrinfo *result = NULL,
                   *ptr    = NULL,
                   hints;
   struct sockaddr *clientInfo = NULL;

   ZeroMemory( &hints, sizeof( hints ) );
   
   hints.ai_family   = AF_INET;     //AF_INET is used to specify the IPv4 address family.
   hints.ai_socktype = SOCK_STREAM; //SOCK_STREAM is used to specify a stream socket.
   hints.ai_protocol = IPPROTO_TCP;  //IPPROTO_TCP is used to specify the TCP protocol.
   hints.ai_flags    = AI_PASSIVE;  //AI_PASSIVE The socket address will be used in a call to the bind function.   

   std::cout << "Getting address info from server.\n";
   iResult = getaddrinfo( NULL, DEFAULT_PORT, &hints, &result );
   if( iResult != 0 ){
      std::cout << "Error in getting address info from server.\nError code: " << iResult << std::endl;
      WSACleanup();
      return 2;
   }
   
   std::cout << "Create SOCKET Object.\n";
   SOCKET ListenSocket = INVALID_SOCKET; //SOCKET object called ListenSocket for the server to listen for client connections.
   std::cout << "Create socket to ip " << result->ai_addr << " at port " << DEFAULT_PORT << ".\n";
   ListenSocket = socket( result->ai_family, result->ai_socktype, result->ai_protocol );
   if( ListenSocket == INVALID_SOCKET ){
      std::cout << "Error creating socket.\nError code: " << WSAGetLastError() << std::endl;
      freeaddrinfo( result );
      WSACleanup();
      return 3;
   }

   std::cout << "Bind listen object to ip, port.\n";
   iResult = bind( ListenSocket, result->ai_addr, result->ai_addrlen );
   if( iResult == SOCKET_ERROR ){
      std::cout << "Binding failed.\nError code: " << WSAGetLastError() << std::endl;
      closesocket( ListenSocket );
      freeaddrinfo( result );
      WSACleanup();
      return 4;
   }
   freeaddrinfo(result); // No need for the result here.

   std::cout << "Start listening with maximum input queue available.\n";
   iResult = listen( ListenSocket, SOMAXCONN );
   if( iResult == SOCKET_ERROR ){
      std:: cout << "Failed start listening.\nError code: " << WSAGetLastError() << std::endl;
      closesocket( ListenSocket );
      freeaddrinfo( result );
      WSACleanup();
      return 5;
   }

   SOCKET ClientSocket = INVALID_SOCKET;
   
   ClientSocket = accept( ListenSocket,clientInfo, NULL );
   if( ClientSocket == INVALID_SOCKET ){
      std::cout << "Failed accepting connection.\nError code: " << WSAGetLastError() << std::endl;
      closesocket( ListenSocket );
      WSACleanup();
      return 6;
   }
   std::cout << "Connection accepted from client\n";

   char recvBuff[DEFAULT_BUFLEN];
   int recvBuffLen = DEFAULT_BUFLEN;
   int iSendResult;

   do{
      iResult = recv( ClientSocket, recvBuff, recvBuffLen, 0 );
      if( iResult > 0 ){
         std::cout << "Message recieved: " << recvBuff << "\nTotal " << iResult << " bytes.\n";
         iSendResult = send( ClientSocket, "This is a response...", 27, 0 );
         if( iSendResult == SOCKET_ERROR ){
            std::cout << "Sending data failed.\nError code: " << WSAGetLastError() << std::endl;
            closesocket( ClientSocket );
            WSACleanup();
            return 7;
         }else{
            std::cout << "Sent " << iSendResult << " bytes.\n";
         }
      }else if( iResult == 0 ){
         std::cout << "Closing connection... " << std::endl;
      }else{
         std::cout << "Recieving failed.\nError code: " << WSAGetLastError() << std::endl;
         closesocket( ListenSocket );
         WSACleanup();
         return 8;
      }
   }while( iResult > 0 );

   iResult = shutdown( ClientSocket, SD_BOTH );
   if( iResult == SOCKET_ERROR ){
      std::cout << "shutdown client failed.\nError code: " << WSAGetLastError() << std::endl;
      closesocket( ClientSocket );
      WSACleanup();
      return 9;
   }
   closesocket( ClientSocket );
   WSACleanup();
}


CLIENT:
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
110
111
112
113
114
#include <iostream>
#include <winsock2.h>
#include <ws2tcpip.h>
#include <stdlib.h>
#include <stdio.h>

// Need to link with Ws2_32.lib, Mswsock.lib, and Advapi32.lib

#define DEFAULT_BUFLEN 512
#define DEFAULT_PORT "27015"

int main() {
    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;
    
    // Initialize Winsock
    iResult = WSAStartup(MAKEWORD(2,2), &wsaData);
    if (iResult != 0) {
        printf("WSAStartup failed: %d\n", iResult);
        return 1;
    }

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

    // Resolve the server address and port
    iResult = getaddrinfo("127.0.0.1", DEFAULT_PORT, &hints, &result);
    if ( iResult != 0 ) {
        printf("getaddrinfo failed: %d\n", iResult);
        WSACleanup();
        return 1;
    }

    // Attempt to connect to an address until one succeeds
    for(ptr=result; ptr != NULL ;ptr=ptr->ai_next) {

        // Create a SOCKET for connecting to server
        ConnectSocket = socket(ptr->ai_family, ptr->ai_socktype, 
            ptr->ai_protocol);
        if (ConnectSocket == INVALID_SOCKET) {
            printf("Error at socket(): %ld\n", WSAGetLastError());
            freeaddrinfo(result);
            WSACleanup();
            return 1;
        }

        // 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("Unable to connect to server!\n");
        WSACleanup();
        return 1;
    }

    // Send an initial buffer
    iResult = send( ConnectSocket, sendbuf, (int)strlen(sendbuf), 0 );
    if (iResult == SOCKET_ERROR) {
        printf("send failed: %d\n", WSAGetLastError());
        closesocket(ConnectSocket);
        WSACleanup();
        return 1;
    }

    printf("Bytes Sent: %ld\n", iResult);

    // shutdown the connection since no more data will be sent
    iResult = shutdown(ConnectSocket, SD_SEND);
    if (iResult == SOCKET_ERROR) {
        printf("shutdown failed: %d\n", WSAGetLastError());
        closesocket(ConnectSocket);
        WSACleanup();
        return 1;
    }

    // Receive until the peer closes the connection
    do {

        iResult = recv(ConnectSocket, recvbuf, recvbuflen, 0);
        if ( iResult > 0 ){
           printf("Bytes received: %d\n", iResult);
           std::cout << "Received data = " << recvbuf;
        }else if ( iResult == 0 ){
           printf("Connection closed\n");
        }else{
           printf("recv failed: %d\n", WSAGetLastError());
        }

    } while( iResult > 0 );

    // cleanup
    closesocket(ConnectSocket);
    WSACleanup();

    return 0;
}


Change it as you need to save your responses to a file.
Last edited on
Topic archived. No new replies allowed.