943,560 Members | Top Members by Rank

Ad:
  • C++ Discussion Thread
  • Unsolved
  • Views: 5790
  • C++ RSS
You are currently viewing page 1 of this multi-page discussion thread
Nov 15th, 2006
0

Connecting to a computer via sockets

Expand Post »
Hi, I'm relatively new to socket programming in C/C++ but i have read a few tutorials and had a good go at trying to do it. I have got to the point where i have created a kind server that will accept incoming connections and then when the data is recieved, it will display a message box containing the data it recieved as a string.

Server code:
C++ Syntax (Toggle Plain Text)
  1. #include <winsock.h>
  2. #include <windows.h>
  3.  
  4. void LastError(LPTSTR lpszFunction)
  5. {
  6. LPVOID lpMsgBuf;
  7. LPVOID lpDisplayBuf;
  8.  
  9. DWORD dw = GetLastError();
  10.  
  11. FormatMessage(
  12. FORMAT_MESSAGE_ALLOCATE_BUFFER |
  13. FORMAT_MESSAGE_FROM_SYSTEM,
  14. NULL,
  15. dw,
  16. MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
  17. (LPTSTR) &lpMsgBuf,
  18. 0, NULL );
  19.  
  20. lpDisplayBuf = (LPVOID)LocalAlloc(LMEM_ZEROINIT,
  21. (lstrlen((LPCTSTR)lpMsgBuf)+lstrlen((LPCTSTR)lpszFunction)+40)*sizeof(TCHAR));
  22. wsprintf((LPTSTR)lpDisplayBuf,
  23. TEXT("%s failed with error %d: %s"),
  24. lpszFunction, dw, lpMsgBuf);
  25. MessageBox(NULL, (LPCTSTR)lpDisplayBuf, TEXT("Message Server"), MB_OK);
  26.  
  27. LocalFree(lpMsgBuf);
  28. LocalFree(lpDisplayBuf);
  29. }
  30.  
  31. HWND hwnd; //this will later be used for the window handle when the interface is implemented
  32. char * ipaddress; //Temp variable, not yet used...
  33.  
  34. int main ()
  35. {
  36. WSADATA wsaData;
  37. if (WSAStartup(MAKEWORD(1, 1), &wsaData) != 0)
  38. {
  39. LastError("WSAStartup()");
  40. exit(1);
  41. }
  42.  
  43. SOCKET listeningSocket;
  44. listeningSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
  45. if (listeningSocket == INVALID_SOCKET)
  46. {
  47. LastError("socket()");
  48. exit(1);
  49. }
  50.  
  51. SOCKADDR_IN serverInfo;
  52. serverInfo.sin_family = AF_INET;
  53. serverInfo.sin_addr.s_addr = INADDR_ANY;
  54. serverInfo.sin_port = htons(1243);
  55.  
  56. int ret = bind(listeningSocket, (LPSOCKADDR)&serverInfo, sizeof(struct sockaddr));
  57. if (ret == SOCKET_ERROR)
  58. {
  59. LastError("bind()");
  60. exit(1);
  61. }
  62.  
  63. ret = listen(listeningSocket,1);
  64. if (ret == SOCKET_ERROR)
  65. {
  66. LastError("listen()");
  67. exit(1);
  68. }
  69.  
  70. SOCKET client;
  71. client = accept(listeningSocket,NULL,NULL);
  72. if (client == INVALID_SOCKET)
  73. {
  74. LastError("accept()");
  75. send(listeningSocket,"true",4,0);
  76. exit(1);
  77. }
  78.  
  79. char buffer[256];
  80. ret = recv(listeningSocket,buffer,256,0);
  81. if (ret == SOCKET_ERROR)
  82. {
  83. LastError("recv()");
  84. }
  85. else
  86. {
  87. MessageBox(hwnd,buffer,"Message Server",MB_ICONEXCLAMATION);
  88. }
  89.  
  90. closesocket(client);
  91. closesocket(listeningSocket);
  92. }

Client code:

C++ Syntax (Toggle Plain Text)
  1. #include <winsock.h>
  2. #include <windows.h>
  3. #include <stdio.h>
  4.  
  5. void LastError(LPTSTR lpszFunction)
  6. {
  7. LPVOID lpMsgBuf;
  8. LPVOID lpDisplayBuf;
  9.  
  10. DWORD dw = GetLastError();
  11.  
  12. FormatMessage(
  13. FORMAT_MESSAGE_ALLOCATE_BUFFER |
  14. FORMAT_MESSAGE_FROM_SYSTEM,
  15. NULL,
  16. dw,
  17. MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
  18. (LPTSTR) &lpMsgBuf,
  19. 0, NULL );
  20.  
  21. lpDisplayBuf = (LPVOID)LocalAlloc(LMEM_ZEROINIT,
  22. (lstrlen((LPCTSTR)lpMsgBuf)+lstrlen((LPCTSTR)lpszFunction)+40)*sizeof(TCHAR));
  23. wsprintf((LPTSTR)lpDisplayBuf,
  24. TEXT("Function '%s' failed with error %d: %s"),
  25. lpszFunction, dw, lpMsgBuf);
  26. MessageBox(NULL, (LPCTSTR)lpDisplayBuf, TEXT("Error"), MB_ICONERROR);
  27.  
  28. LocalFree(lpMsgBuf);
  29. LocalFree(lpDisplayBuf);
  30. }
  31.  
  32.  
  33. HWND hwnd;
  34. char * serverAddress="127.0.0.1";
  35. char buffer[256]="This is the message";
  36. int ret;
  37.  
  38. int main ()
  39. {
  40. WSADATA wsaData;
  41. ret = WSAStartup(MAKEWORD(1, 1), &wsaData);
  42. if (ret != 0)
  43. {
  44. LastError("WSAStartup()");
  45. exit(1);
  46. }
  47.  
  48. LPHOSTENT hostEntry;
  49. in_addr iaHost;
  50. iaHost.s_addr = inet_addr(serverAddress);
  51. hostEntry = gethostbyaddr((const char *)&iaHost, sizeof(struct in_addr), AF_INET);
  52.  
  53. if (!hostEntry)
  54. {
  55. LastError("gethostbyaddr()");
  56. exit(1);
  57. }
  58.  
  59. SOCKET sendingSocket;
  60. sendingSocket = socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);
  61. if (sendingSocket == INVALID_SOCKET)
  62. {
  63. LastError("socket()");
  64. exit(1);
  65. }
  66.  
  67. SOCKADDR_IN serverInfo;
  68. serverInfo.sin_family = AF_INET;
  69. serverInfo.sin_port = htons(1243);
  70. serverInfo.sin_addr = *((LPIN_ADDR)*hostEntry->h_addr_list);
  71.  
  72. ret = connect(sendingSocket,(LPSOCKADDR)&serverInfo,sizeof(struct sockaddr));
  73. if (ret == SOCKET_ERROR)
  74. {
  75. LastError("connect()");
  76. exit(1);
  77. }
  78.  
  79. ret = send(sendingSocket,buffer,256,0);
  80. if (ret == SOCKET_ERROR)
  81. {
  82. LastError("send()");
  83. exit(1);
  84. }
  85. else
  86. {
  87.  
  88. MessageBox(hwnd,"Message has been sent successfully","Client",MB_ICONINFORMATION);
  89.  
  90. /* char temp[100]; //not yet finished, ignore this..
  91.   sprintf(temp,"%d BYTES sent",ret);
  92.   MessageBox(0,temp,0,0); */
  93. }
  94.  
  95. closesocket(sendingSocket);
  96.  
  97. }

For now I am using the loopback IP address to I can connect the server and client on the same computer using a random port number "1243".

Currently the server runs fine and the client does also, but when I run the client, and the message is sent, the server does not seem to recieve the message correctly since a message is displayed saying "recv() failed with error 10057: A request to send or recieve data was disallowed because the socket is not connected and (when sending on a datagram socket using a sendto call) no address was supplied." So Im assuming there is some kind of mistake in the server program or I am doing something wrong when sending the message.

Secondly, I want to be able to run the server remotely and send a message to it using the client. My problem is that I am behind a router and the destination computer is behind a router also, in fact the same one. We share the same IP address. I want to be able to know how to connect to the server when it is running on a computer behind a router. So basically I want to know how to specify which computer will recieve the data when there are a number of different computers behind the same router.

Thanks.
Similar Threads
Reputation Points: 23
Solved Threads: 5
Posting Whiz in Training
bops is offline Offline
214 posts
since Aug 2005
Nov 15th, 2006
0

Re: Connecting to a computer via sockets

anyone got any suggestions for either of the problems?
Reputation Points: 23
Solved Threads: 5
Posting Whiz in Training
bops is offline Offline
214 posts
since Aug 2005
Nov 17th, 2006
0

Re: Connecting to a computer via sockets

anyone? any suggestions? especially to the IP address problem?
Reputation Points: 23
Solved Threads: 5
Posting Whiz in Training
bops is offline Offline
214 posts
since Aug 2005
Nov 20th, 2006
0

Re: Connecting to a computer via sockets

Why no replies?
Reputation Points: 23
Solved Threads: 5
Posting Whiz in Training
bops is offline Offline
214 posts
since Aug 2005
Nov 20th, 2006
0

Re: Connecting to a computer via sockets

If you want to connect to your own network by going outside and coming back in you need to know your external IP address, and you need to tell your router to forward your port(1234) to your server computers internal ip address.

Then using your client side code try to connect to your external ip address at port 1234
Reputation Points: 36
Solved Threads: 2
Junior Poster in Training
nanodano is offline Offline
78 posts
since Feb 2005
Nov 20th, 2006
0

Re: Connecting to a computer via sockets

Sorry about the delay in the replies. I only look at unanswered threads, so when there were about 3 replies, I skipped the thread. If you hadn't bumped the thread, I probably would have taken a look and replied sooner. Anyway the error is in this line of the server code.

  1. ret = recv(listeningSocket,buffer,256,0);

change it to
  1. ret = recv(client,buffer,256,0);
Moderator
Reputation Points: 572
Solved Threads: 115
Mentally Challenged Mod.
WolfPack is offline Offline
1,559 posts
since Jun 2005
Nov 23rd, 2006
0

Re: Connecting to a computer via sockets

Argh, thanks a lot, I can't believe that the problem was simply writing the name of the wrong socket.

For the IP problem, you know how like any web application that uses sockets, say for MSN Messenger as an example, when you connect to the server and your client application sends requests to the server, and then the server knows exactly where to send the message back to you. I'm assuming they used something along the lines of recvfrom() to do this, but surely if it works without me having to start messin around with the router, then surely I can don't have to do that in order to make mine work.
Reputation Points: 23
Solved Threads: 5
Posting Whiz in Training
bops is offline Offline
214 posts
since Aug 2005
Nov 23rd, 2006
0

Re: Connecting to a computer via sockets

Okay. As you know, the two protocols are the TCP/IP and UDP protocols. TCP creates a connection that is valid throughout the time the server and client corresponds with each other. Like a telephone conversation. But UDP sends packets to an address, and there is no connection that is valid after the data packet is delivered. This is more like sending a letter through mail. The postman delivers it only if there is something to be delivered.

The difference between recv and recvfrom is that they use 2 different protocols. recv uses TCP/IP and recvfrom uses UDP. You can do what you want to do using both the protocols. At any rate you shold know the server IP address.

From what I gather from your previous posts, you are behind a router, but there are 2 computers that use the router to connect to the internet. So the outside world only knows the router, so they see only one IP address. However, both your computers should have 2 different local IP addresses. You can use them as the server and client IP addresses. Try typing "ipconfig" at the command prompt of the 2 computers. You should get the IP addresses of the server and client. If you substitute 127.0.0.1 with the server local IP address, you should be able to connect to the server using the client code.
Moderator
Reputation Points: 572
Solved Threads: 115
Mentally Challenged Mod.
WolfPack is offline Offline
1,559 posts
since Jun 2005
Nov 24th, 2006
0

Re: Connecting to a computer via sockets

Yes thats exactly it. I have tried before entering "ipconfig" at the command line and usually I will see IP assigned to the network, which is something like 192.168.1.65, and i think the loopback IP 127.0.0.1 and I think the address of the router. I am at University at the moment and I will have to re-check this when I get home, but I think that is what shows up, no unique IP address for the local machine. Do you know of any way in which knowing the IP address of the router, and knowing the IP address of my computer on the network 192.168.1.65, that i could use these to connect to it on the port i have chosen in my program, therefore connecting to the router and then in turn connecting to my machine, and to the server running on the port.

I'm glad you understand my query, I find it hard to get across to most people.

Thanks.
Reputation Points: 23
Solved Threads: 5
Posting Whiz in Training
bops is offline Offline
214 posts
since Aug 2005
Nov 24th, 2006
0

Re: Connecting to a computer via sockets

If you get 192.168.1.65 as the server local IP address, inputting that instead of 127.0.0.1 in the client code will get you connected to the server address.

e.g in the client code
C++ Syntax (Toggle Plain Text)
  1. char * serverAddress="192.168.1.65";
Moderator
Reputation Points: 572
Solved Threads: 115
Mentally Challenged Mod.
WolfPack is offline Offline
1,559 posts
since Jun 2005

This thread is more than three months old

No one has posted to this discussion for at least three months. Please let old threads die and do not reply to them unless you feel you have something new and valuable to contribute that absolutely must be added to make the discussion complete. Otherwise, please start a new thread in this forum instead.
Message:
Previous Thread in C++ Forum Timeline: Does constructor create the object ?
Next Thread in C++ Forum Timeline: Nice easy one for you all... passing arrays to functions in C





About Us | Contact Us | Advertise | Acceptable Use Policy
Forum Index | Build Custom RSS Feed


Follow us on Twitter


© 2011 DaniWeb® LLC