Brian D
Brian D

Reputation: 10163

Why might a socket refuse a connection?

I have written an FTP client to automatically enter passive mode and subsequently connect to the server via a given IP and Port.

Usually it works. Sometimes it doesn't.

Do you think it could be because the server hasn't yet had time to open the port? Why else would the server refuse my connection?

int sockfd;
int len;
struct sockaddr_in address;
int result;


/*  Create a socket for the client.  */
sockfd = socket(PF_INET, SOCK_STREAM, 0);

/*  Name the socket, as agreed with the server.  */
address.sin_family = AF_INET;
address.sin_addr.s_addr = inet_addr(  hostname    );
address.sin_port = htons(  port  );
len = sizeof(address);

/*  Now connect our socket to the server's socket.  */
result = connect(sockfd, (struct sockaddr *)&address, len);

if(result == -1) {
    perror("oops (data): client3");
    printf("thread%i %s:%i\n", thread_name, hostname, prt);
    exit(1);
}

Just looking for some insight from anyone with experience in socket programming.

Note: this client is multi-threaded. The idea is to download 1/nth of a file from 1 of n servers. This most-often happens when I try connecting to the same server multiple in multiple threads, but this is not exclusive -- i.e., it can happen with two completely separate servers as well.

EDIT

As it turns out, there was an error in my algorithm. Between parsing the server response (which comes back with an IP and Port in this form: 127,0,0,1,0,20), I somehow forgot to zero out a certain block of memory that I was using and ended up writing over some previous port numbers. When the overwriting number was larger, there was no problem. But, when it was smaller, there were residual numbers left over causing problems. For example:

Last Port Calculation    = 54321
Current Port Calculation = 9876
Current Port Stored as...  98761 <- appending the 1 to the port number

Which led the server to rightfully refuse my connection.

So, in the end, programmer's mistake. :)

Upvotes: 1

Views: 860

Answers (1)

Hiram Chirino
Hiram Chirino

Reputation: 4091

It could also be because the server is not accepting new connections fast enough and his accept buffer is already full.

Upvotes: 2

Related Questions