Solved

WINSOCK PROGRAMMING IN C++

Posted on 2004-10-03
13
17,286 Views
Last Modified: 2013-11-13
Hey there...

When i run the below code, all the error checks say it's ok. However when the program gets into the "accept" loop, it loops forever. I CAN connect to that port, (when the program is not running i can NOT connect to that port), however when i send data to that port the program does not acknowledge the data for some reason. I cannot see what i am doing wrong. Source code below.

=========================================================================================

#include "stdafx.h"
#include "windows.h"
#include <iostream>
#include <string>

#include "WINSOCK2.H"
#pragma comment (lib, "WS2_32.LIB")

const UINT cc_port = 3276;

int _tmain(int argc, _TCHAR* argv[])
{
      WSADATA data;
      SOCKET sock, tmp_sock;
      SOCKADDR_IN local_info, remote_info;
      int cLen;

      std::cout << "attempting to initalize... ";
      if(WSAStartup(MAKEWORD(2,2), &data))
      {
            std::cout << "failed\n";
            getchar();
            return 0;
      }
      std::cout << "ok\n";
      
      std::cout << "attempting to create socket...";
      sock = socket(AF_INET, SOCK_STREAM, 0);

      if(sock == SOCKET_ERROR)
      {
            std::cout << "failed\n";
            getchar();
            return 0;
      }
      std::cout << "ok\n";

      local_info.sin_family = AF_INET;
      local_info.sin_port = htons(cc_port);
      local_info.sin_addr.s_addr = htons(INADDR_ANY);
      
      std::cout << "attempting to bind... ";
      if(bind(sock, (SOCKADDR*) &local_info, sizeof(SOCKADDR_IN)) == SOCKET_ERROR)
      {
            std::cout << "failed\n";
            getchar();
            return 0;
      }
      std::cout << "ok\n";

      std::cout << "attempting to prepare socket for listening... ";
      if(listen(sock, 5) == SOCKET_ERROR)
      {
            std::cout << "failed\n";
            getchar();
            return 0;
      }
      std::cout << "ok\n";

      std::cout << "attempting to listen for a connection";
      do
      {
            tmp_sock = accept(sock, (SOCKADDR*) &remote_info, &cLen);
            std::cout << "!";
      }
      while(tmp_sock == SOCKET_ERROR);
      std::cout << "\nconnection recived!!!!!!!!!!!!!!!";

      closesocket(sock);
      closesocket(tmp_sock);
      WSACleanup();

      getchar();
      return 0;
}

=========================================================================================

Any suggestions would be much appreciated,
SOUTHERN CURRIEZ
0
Comment
Question by:da_mango_bros
  • 4
  • 4
  • 3
  • +1
13 Comments
 
LVL 1

Expert Comment

by:lubovec
Comment Utility
hi da_mango_bros

you need not use the accept loop, because your socket is in blocked mode. that means function accept is blocking execution of program before connection is recieved. it is not error

try replace this part of code

     do
     {
          tmp_sock = accept(sock, (SOCKADDR*) &remote_info, &cLen);
          std::cout << "!";
     }
     while(tmp_sock == SOCKET_ERROR);
     std::cout << "\nconnection recived!!!!!!!!!!!!!!!";

by this

     tmp_sock = accept(sock, (SOCKADDR*) &remote_info, &cLen);
     std::cout << "!";
     std::cout << "\nconnection recived!!!!!!!!!!!!!!!";

good luck

bye

PS: i hope my english is understandable ;)
0
 
LVL 7

Expert Comment

by:dttri
Comment Utility
 Hello,
  After you send data to the program, what the program response? It end or whatever?

  Tri
0
 

Author Comment

by:da_mango_bros
Comment Utility
Hey thanks for replying.

lubovec:

Something seems to be seriously wrong. I removed the loop as you said, but after running it immediately said "connection recived" even though i had not sent anything to that port.

When i had the loop, it just put out long strings of "!" to indicate that each time accept() was failing and immediately being called again.


dttri:

At this stage, i just want it to print the data on the screen and then exit. Before i code any more i want to make sure the basics are working.  

0
 
LVL 1

Expert Comment

by:lubovec
Comment Utility

question is, how client are you using to test this server... if you have your own client, try to post its source code...
0
 
LVL 19

Expert Comment

by:drichards
Comment Utility
Your accept will fail because you have not set cLen properly.  Add 'cLen = sizeof(SOCKADDR_IN);' before the do loop and the accept should work.  Then you will need to add code to recevie the data.
0
 
LVL 7

Accepted Solution

by:
dttri earned 125 total points
Comment Utility
>>>Your accept will fail because you have not set cLen properly.  Add 'cLen = sizeof(SOCKADDR_IN);' before the do loop and the accept should work.  Then you will need to add code to recevie the data.

That's correct! But if you want to receive data more than 1 times (or in case the first receive fail), but 'cLen=sizeof(SOCKADDR_IN);' at the first line in the loop.
This info is from MSDN:

"SOCKET accept(
  SOCKET s,
  struct SOCK_ADDR* addr,
  int FAR* addrlen
);
The integer referred to by addrlen initially contains the amount of space pointed to by addr. On return, it will contain the actual length in bytes of the address returned."

0
Highfive Gives IT Their Time Back

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

 
LVL 19

Expert Comment

by:drichards
Comment Utility
>> But if you want to receive data more than 1 times (or in case the first receive fail), but 'cLen=sizeof(SOCKADDR_IN);' at the first line in the loop.
Not really necessary because the returned size will be the same since it will be returning a SOCKADDR_IN.  cLen should not be set on fail.
0
 
LVL 1

Expert Comment

by:lubovec
Comment Utility

finaly everything is so simple :)
0
 

Author Comment

by:da_mango_bros
Comment Utility
well i added 'cLen = sizeof(SOCKADDR_IN);', and then it worked fine - there was no need for the loop.

however from dttri's previous comment i think i may still have a problem.

i am trying to make a peer-2-peer chat program, and i need to be able to have more than one connection open at the same time.


so if i just accept the first connection and go ahead and send/recive data, how will i know when someone else is trying to establish a connection with me?

also if i have a continuous loop checking if someone wants to connect, how will i be able to go ahead and send/recive data?
0
 
LVL 7

Assisted Solution

by:dttri
dttri earned 125 total points
Comment Utility
 Hello,
  If you need your program to be able to accept connection and also send and receive data, you may use multithreaded, for example: your main thread will wait and accept connections, if it receive 1 connection and it will create a new thread to handle this connection.
  You can view the simple source here:
http://tangentsoft.net/wskfaq/examples/basics/threaded-server.cpp
  The code project article about multithreaded TCP server:
http://www.codeproject.com/internet/winsockintro03.asp
  And this discussion may be useful:
http://forums.devshed.com/showthread.php?t=169115

  Tri
0
 

Author Comment

by:da_mango_bros
Comment Utility
ok thankz i should have no problems making it now
0
 
LVL 7

Expert Comment

by:dttri
Comment Utility
 Hello,
  Can you request the Mod to split the points to drichards for me? Because he found 'cLen = sizeof(SOCKADDR_IN);' for you.

  Regards,
  Tri
0
 

Author Comment

by:da_mango_bros
Comment Utility
ahh yes... i missed that before (probably because everyone posted at once and i didnt look at the names).

will request to the mod
0

Featured Post

Highfive Gives IT Their Time Back

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

Join & Write a Comment

Does the idea of dealing with bits scare or confuse you? Does it seem like a waste of time in an age where we all have terabytes of storage? If so, you're missing out on one of the core tools in every professional programmer's toolbox. Learn how to …
Since upgrading to Office 2013 or higher installing the Smart Indenter addin will fail. This article will explain how to install it so it will work regardless of the Office version installed.
This tutorial will introduce the viewer to VisualVM for the Java platform application. This video explains an example program and covers the Overview, Monitor, and Heap Dump tabs.
The viewer will be introduced to the member functions push_back and pop_back of the vector class. The video will teach the difference between the two as well as how to use each one along with its functionality.

744 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

16 Experts available now in Live!

Get 1:1 Help Now