Sockets: client cannot connect to other computer/server

hi,
I have a problem, and so far I don't know how to get through it.
I have created standard server and client by windows sockets and it works fine on my PC (if I run server and then run client they connect) but I don't know how to make it working also when server is running on the computer of my friend (he runs server part) and client is started on my PC.
his IP: 192.168.1.6
my IP: 192.168.1.2
Why I cant connect to my server application running on his machine?
Should it works? Do I have to do sth else in addition to establish connection?

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
// C++ from Visual Studio 2008 Pro Edition
	//#include "stdafx.h"
	#include <winsock2.h>
	#include <ws2tcpip.h>
	#include <stdio.h>
	#include <windows.h>
	//#pragma comment(lib, "ws2_32.lib") //not necessary becouse additional dependency added to linker
// Microsoft Development Environment 2003 - Version 7.1.3088
// Copyright (r) 1987-2002 Microsoft Corporation. All Right Reserved
// Microsoft .NET Framework 1.1 - Version 1.1.4322
// Copyright (r) 1998-2002 Microsoft Corporation. All Right Reserved
// Run on Windows XP Pro machine, version 2002, SP 2
// <windows.h> already included
// WINVER = 0x0501 for Xp already defined in windows.h
 

int main(){
WORD wVersionRequested;
WSADATA wsaData={0};
int wsaerr;

// Using MAKEWORD macro, Winsock version request 2.2
wVersionRequested = MAKEWORD(2, 2);
wsaerr = WSAStartup(wVersionRequested, &wsaData);
if (wsaerr != 0){
    /* Tell the user that we could not find a usable WinSock DLL.*/
    printf("Server: The Winsock dll not found!\n");
    return 0;
}else{
       printf("Server: The Winsock dll found!\n");
       printf("Server: The status: %s.\n", wsaData.szSystemStatus);
}

/* Confirm that the WinSock DLL supports 2.2.*/
/* Note that if the DLL supports versions greater    */
/* than 2.2 in addition to 2.2, it will still return */
/* 2.2 in wVersion since that is the version we      */
/* requested.                                        */
if (LOBYTE(wsaData.wVersion) != 2 || HIBYTE(wsaData.wVersion) != 2 ){
/* Tell the user that we could not find a usable WinSock DLL.*/
printf("Server: The dll do not support the Winsock version %u.%u!\n", LOBYTE(wsaData.wVersion), HIBYTE(wsaData.wVersion));
       WSACleanup();
       return 0;
}else{
       printf("Server: The dll supports the Winsock version %u.%u!\n", LOBYTE(wsaData.wVersion), HIBYTE(wsaData.wVersion));
       printf("Server: The highest version this dll can support: %u.%u\n", LOBYTE(wsaData.wHighVersion), HIBYTE(wsaData.wHighVersion));
}
//////////Create a socket////////////////////////
//Create a SOCKET object called m_socket.
SOCKET m_socket;
// Call the socket function and return its value to the m_socket variable.
// For this application, use the Internet address family, streaming sockets, and the TCP/IP protocol.
// using AF_INET family, TCP socket type and protocol of the AF_INET - IPv4
m_socket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);

// Check for errors to ensure that the socket is a valid socket.
if (m_socket == INVALID_SOCKET){
    printf("Server: Error at socket(): %ld\n", WSAGetLastError());
    WSACleanup();
    //return 0;
}else{
    printf("Server: socket() is OK!\n");
}

////////////////bind//////////////////////////////
// Create a sockaddr_in object and set its values.
sockaddr_in service;

// AF_INET is the Internet address family.
service.sin_family = AF_INET;
// "127.0.0.1" is the local IP address to which the socket will be bound.
service.sin_addr.s_addr = htons(INADDR_ANY); //inet_addr("192.168.1.2");
// 55555 is the port number to which the socket will be bound.
// using the htons for big-endian
service.sin_port = htons(55555);

// Call the bind function, passing the created socket and the sockaddr_in structure as parameters.
// Check for general errors.
if (bind(m_socket, (SOCKADDR*)&service, sizeof(service)) == SOCKET_ERROR){
    printf("Server: bind() failed: %ld.\n", WSAGetLastError());
    closesocket(m_socket);
    //return 0;
}else{
    printf("Server: bind() is OK!\n");
}
// Call the listen function, passing the created socket and the maximum number of allowed
// connections to accept as parameters. Check for general errors.
if (listen(m_socket, 1) == SOCKET_ERROR)
       printf("Server: listen(): Error listening on socket %ld.\n", WSAGetLastError());
else{
    printf("Server: listen() is OK, I'm waiting for connections...\n");
}

// Create a temporary SOCKET object called AcceptSocket for accepting connections.
SOCKET AcceptSocket;

// Create a continuous loop that checks for connections requests. If a connection
// request occurs, call the accept function to handle the request.
printf("Server: Waiting for a client to connect...\n");
printf("***Hint: Server is ready...run your client program...***\n");
// Do some verification...
while (1){
    AcceptSocket = SOCKET_ERROR;

      while (AcceptSocket == SOCKET_ERROR){
        AcceptSocket = accept(m_socket, NULL, NULL);
       }
   // else, accept the connection...
   // When the client connection has been accepted, transfer control from the
   // temporary socket to the original socket and stop checking for new connections.
    printf("Server: Client Connected!\n");
    m_socket = AcceptSocket;
    break;
}
system("pause");
return 0;
}


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
// C++ from Visual Studio 2008 Pro Edition
	//#include "stdafx.h"
	#include <winsock2.h>
	#include <ws2tcpip.h>
	#include <stdio.h>
	#include <windows.h>
	//#pragma comment(lib, "ws2_32.lib") //not necessary becouse additional dependency added to linker
    // Microsoft Development Environment 2003 - Version 7.1.3088
    // Copyright (r) 1987-2002 Microsoft Corporation. All Right Reserved
    // Microsoft .NET Framework 1.1 - Version 1.1.4322
    // Copyright (r) 1998-2002 Microsoft Corporation. All Right Reserved
    // Run on Windows XP Pro machine, version 2002, SP 2
    // <windows.h> already included
    // WINVER = 0x0501 for Xp already defined in windows.h
    // A sample of client program

    int main(){
        // Initialize Winsock.
        WSADATA wsaData;
        int iResult = WSAStartup(MAKEWORD(2,2), &wsaData);
        if (iResult != NO_ERROR)
             printf("Client: Error at WSAStartup().\n");
        else
             printf("Client: WSAStartup() is OK.\n");
        // Create a socket.
        SOCKET m_socket;
        m_socket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);

        if (m_socket == INVALID_SOCKET){
            printf("Client: socket() - Error at socket(): %ld\n", WSAGetLastError());
            WSACleanup();
            return 7;
		}else
           printf("Client: socket() is OK.\n");

        // Connect to a server.
        sockaddr_in clientService;
     
        clientService.sin_family = AF_INET;
        //clientService.sin_addr.s_addr = inet_addr("77.64.240.156");
		clientService.sin_addr.s_addr = inet_addr("192.168.1.6");
        clientService.sin_port = htons(55555);

        if (connect(m_socket, (SOCKADDR*)&clientService, sizeof(clientService)) == SOCKET_ERROR){
            printf("Client: connect() - Failed to connect.\n");
            WSACleanup();
            return 6;
        }

        // Send and receive data
        int bytesSent;
        int bytesRecv = SOCKET_ERROR;
        // Be careful with the array bound, provide some checking mechanism
        char sendbuf[200] = "Client: Sending some test string to server...";
        char recvbuf[200] = "";

        bytesSent = send(m_socket, sendbuf, strlen(sendbuf), 0);
        printf("Client: send() - Bytes Sent: %ld\n", bytesSent);

        while(bytesRecv == SOCKET_ERROR){
            bytesRecv = recv(m_socket, recvbuf, 32, 0);
            if (bytesRecv == 0 || bytesRecv == WSAECONNRESET){
                printf("Client: Connection Closed.\n");
                break;
            }else
                printf("Client: recv() is OK.\n");

            if (bytesRecv < 0)
                return 0;
            else
                printf("Client: Bytes received - %ld.\n", bytesRecv);
        }
		system("pause");
        return 0;
    }

Last edited on
Are both PC's in the same network? BTW, I'm not a network guy. I barely know anything on this subject, but since you mention your "friend" and not your relative, I am bound to think that the most likely scenario is that your PC is at your home and your friend's PC is at your friend's home, and those IP's are private and therefore not reachable between one another. Are you two in the same household using the same network?
yes, we are in the same household
sorry, I've made mistake providing IP, now it is correct:
his IP: 192.168.1.6
my IP: 192.168.1.2
Last edited on
Do you have a fire wall between the two computers? One thing that will really help you when debugging socket programs is to download "Wire Shark". That program will really come in handy!
My first question is how do you know it isn't connecting? Your server doesn't try to recieve any data even though your client is sending it text AND waiting for a response.

This code should not work if both applications are run on the same PC unless the address your client is connecting to is being set to loop back or something. This is the first thing I would check. You can use "tcpview" from the Sysinternals suite to check the connections that running applications have open: http://technet.microsoft.com/en-us/sysinternals/bb842062
@kooth, @Computergeek01: thank you very much for your cues. I said that there is no connection between client and erver base on the fact, that I don't get message "Server: Client Connected!" from printf, which is to be triggered on accept().
I get this message if both applications are running on my machine. Isn't it OK?

1
2
3
4
5
6
7
8
9
10
11
12
13
while (1){
    AcceptSocket = SOCKET_ERROR;

      while (AcceptSocket == SOCKET_ERROR){
        AcceptSocket = accept(m_socket, NULL, NULL);
       }
   // else, accept the connection...
   // When the client connection has been accepted, transfer control from the
   // temporary socket to the original socket and stop checking for new connections.
    printf("Server: Client Connected!\n");
    m_socket = AcceptSocket;
    break;
}


moreover, client returns "Client: connect() - Failed to connect."
1
2
3
4
5
if (connect(m_socket, (SOCKADDR*)&clientService, sizeof(clientService)) == SOCKET_ERROR){
            printf("Client: connect() - Failed to connect.\n");
            WSACleanup();
            return 6;
        }


I suspect it might be sth with LAN. socket is created on port 55555 by friend's server and it is listening to: I have checked this by netstat -a 5. the problem is my client on my computer can't see it. I have noticed that sometimes I can ping his address but sometimes not. Is it right to state, that if there is no ping then there is no option for connect by socket?
Last edited on
I'd suggest that you print the error (with WSAGetLastError()) to know what kind of error appeared.

Like this:
MSDN wrote:
With a nonblocking socket, the connection attempt cannot be completed immediately. In this case, this function will return SOCKET_ERROR and WSAGetLastError will return WSAEWOULDBLOCK. The following list shows the three scenarios that are possible in this case:
Topic archived. No new replies allowed.