Tcp socket

Pages: 12
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
void client (string ip, int port, string msg) {

    #ifdef WIN32
    WSADATA wsaData;
    if ((WSAStartup(MAKEWORD(2,2), &wsaData)!=0)) {
        cout << CL_WSA_ERR;
        return;
    }
	#endif

    SOCKET sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
    if(sock<0) {
        cout << CL_SOCK_ERR;
        return;
    } else cout << CL_SOCK_OK;

    sockaddr_in client_addr;

    client_addr.sin_family=AF_INET;
    client_addr.sin_addr.s_addr = inet_addr(ip.c_str());
    client_addr.sin_port=htons(port);

    struct timeval tv;
    tv.tv_sec = 5;
    setsockopt(sock, SOL_SOCKET, SO_RCVTIMEO,(char *)&tv,sizeof(struct timeval));

    if(connect(sock, (struct sockaddr *)&client_addr, sizeof(client_addr))<0) {
        cout << "\nconnect - " << strerror(errno) << "\n";
        return;
    }//cout << CL_CONNECT_ERR;
    else cout << CL_CONNECT_OK;

    char buffer[100];
    int s = send(sock, msg.c_str(), msg.size()+1, 0);
        if(s<0) {
            cout << "\nsend - " << strerror(errno) << " - " << errno << "\n"; //cout << CL_SEND_ERR;
            #ifdef __linux__
            close(sock);
            #else
            closesocket(sock); WSACleanup();
            #endif
            return;
        }

    int r = recv(sock, buffer, sizeof(buffer), 0);
    if(r) {
        buffer[r]='\0',
        cout << "Received:" << buffer << endl;
    }

    #ifdef __linux__
    close(sock);
    #else
    closesocket(sock); WSACleanup();
    #endif
return;
}
Last edited on
recv() can return -1; you don't check for it.

You should pass in the strings by const ref.

I can't see how this code relates to the earlier discussion.
I had tried the same test with the same function but adapted for udp datagram and everything is fine no memory increase.. seems like it's a tcp thing.
Last edited on
Topic archived. No new replies allowed.
Pages: 12