0

I'm using the connect function (http://linux.die.net/man/2/connect) and it only works sometimes. It used to work correctly all the time before, now it hardly ever works. The code hasn't changed since I first wrote it about 2 weeks ago so the result shouldn't be changing. I'm thinking it has to do with my network. I'm using port 5301 (pretty much chosen at random) so maybe there's some sort of blocking going on? I'm using the local IP 127.0.0.1.

Code for the server:

    int connectionID = 0, listenID = 0;                         
    struct sockaddr_in sad;
    listenID = socket (AF_INET, SOCK_STREAM, 0);                         
    memset (&sad, 0, sizeof(sad));          
    sad.sin_family = AF_INET;                                
    sad.sin_addr.s_addr = INADDR_ANY;                       
    sad.sin_port = htons(5301);    
    bind (listenID, (struct sockaddr *)&sad, sizeof(sad));

Code for the client:

    int sockID = 0;     
    struct sockaddr_in sad;
    sockID = socket (AF_INET, SOCK_STREAM, 0); 
    sad.sin_family = AF_INET; 
    sad.sin_port = htons(5301);
    inet_pton (AF_INET, serverIP, &sad.sin_addr.s_addr);
    if (connect (sockID, (struct sockaddr *)&sad, sizeof(sad)) < 0)
    {
         printf ("Error Connecting to Server\n");
         return;
    }

The IP is passed in as a parameter

user2929779
  • 359
  • 5
  • 13
  • What is the error when the connection is not created? That might point some light on the subject. :) – KeithSmith Dec 02 '13 at 05:01
  • Connection Refused is what errno spits out. It's random, it just worked twice in a row. But not once in the 50 tries before. – user2929779 Dec 02 '13 at 05:16

1 Answers1

1

It's hard to tell exactly what the problem is, but if the client suddenly reports "Connection refused" then it's likely that the server is no longer listening.

The server should check the return value from bind for any errors, to find out if it was unable to bind to port 5301 for any reason. The server code you have posted here doesn't check for any errors that might arise.

Tim Pierce
  • 5,514
  • 1
  • 15
  • 31
  • Yeah it's not binding. Errno says Address already in use. How are you supposed to properly close an connection? – user2929779 Dec 02 '13 at 05:33
  • @user2929779 There are many questions on Stack Overflow that discuss how to resolve "Address already in use". See http://stackoverflow.com/questions/1592055/bind-address-already-in-use for some. I also recommend W. Richard Stevens' book _Unix Network Programming_ for a comprehensive approach to this issue. – Tim Pierce Dec 02 '13 at 16:06