Anton
Anton

Reputation: 4403

What is wrong with my sockets code?

I'm working on an iOS version of my Android application which constantly sends some binary data to server over regular TCP connection. And while Java code works fine, my code in plain C doesn't - the connection breaks after the first bunch of data is sent to server. I managed to reimplement Java solution using CFNetwork framework, however my C code is still a problem...

C code (error checking and uninteresting code is removed):

mSocket = socket(AF_INET, SOCK_STREAM, 0);
//...        
connect(mSocket, (struct sockaddr *)&sin, sizeof(sin));
int keepalive = 1;  
int res = setsockopt(mSocket, SOL_SOCKET, SO_KEEPALIVE, (void *)&keepalive, 
                          sizeof(int));

int set = 1;
setsockopt(mSocket, SOL_SOCKET, SO_NOSIGPIPE, (void *)&set, sizeof(int));

unsigned char buffer* = //...;
int ret = send(mSocket, buffer, bufferLen, 0);  //handshake with server, runs fine

while(/*there is new data*/) {
       buffer = new_data(); //some fake method
       ret = send(mSocket, buffer, bufferLen, 0); //On the second iteration 
                                                  //write returns -1
}

However, this Objective-C code based on CFNetwork works just fine...

Objective-C code:

 CFStreamCreatePairWithSocketToHost(kCFAllocatorDefault, 
                                   host, 
                                   port, 
                                   &readStream, 
                                   &writeStream);
 CFWriteStreamOpen(mServerWriteStream);

 while(/*there is new data*/) {
     NSData* data = //....
     int wroteBytes = CFWriteStreamWrite(mServerWriteStream, [data bytes], [data length]);
 }

So I'm puzzled with what am I doing wrong in C code and will appreciate any hints

Thank you

Upvotes: 1

Views: 741

Answers (2)

Ray
Ray

Reputation: 1

The setsockopt() has to execute before connect() or it is ignored.

Upvotes: 0

Fred
Fred

Reputation: 17085

If you need a regular TCP connection you need to create the socket with such protocol. Instead of:

mSocket = socket(AF_INET, SOCK_STREAM, 0);

You should create it as:

#include <netinet/in.h>
mSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);

On my system IPPROTO_TCP is defined as 6 and not 0. I suspect you have something similar.

Upvotes: 2

Related Questions