Solved

WINSOCK PROGRAMMING IN C++

Posted on 2004-10-03
13
17,318 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 4
  • 4
  • 3
  • +1
13 Comments
 
LVL 1

Expert Comment

by:lubovec
ID: 12211150
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
ID: 12211228
 Hello,
  After you send data to the program, what the program response? It end or whatever?

  Tri
0
 

Author Comment

by:da_mango_bros
ID: 12211357
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
Get 15 Days FREE Full-Featured Trial

Benefit from a mission critical IT monitoring with Monitis Premium or get it FREE for your entry level monitoring needs.
-Over 200,000 users
-More than 300,000 websites monitored
-Used in 197 countries
-Recommended by 98% of users

 
LVL 1

Expert Comment

by:lubovec
ID: 12211813

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
ID: 12212281
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
ID: 12212591
>>>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
 
LVL 19

Expert Comment

by:drichards
ID: 12212658
>> 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
ID: 12212900

finaly everything is so simple :)
0
 

Author Comment

by:da_mango_bros
ID: 12214177
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
ID: 12214459
 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
ID: 12214815
ok thankz i should have no problems making it now
0
 
LVL 7

Expert Comment

by:dttri
ID: 12215266
 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
ID: 12215611
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

Want Experts Exchange at your fingertips?

With Experts Exchange’s latest app release, you can now experience our most recent features, updates, and the same community interface while on-the-go. Download our latest app release at the Android or Apple stores today!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

This is about my first experience with programming Arduino.
If you’re thinking to yourself “That description sounds a lot like two people doing the work that one could accomplish,” you’re not alone.
Viewers will learn how to properly install Eclipse with the necessary JDK, and will take a look at an introductory Java program. Download Eclipse installation zip file: Extract files from zip file: Download and install JDK 8: Open Eclipse and …
In this seventh video of the Xpdf series, we discuss and demonstrate the PDFfonts utility, which lists all the fonts used in a PDF file. It does this via a command line interface, making it suitable for use in programs, scripts, batch files — any pl…

617 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