Bad file descriptor with BSD socket - sockets

I keep getting a "Bad file descriptor" error when I try to send data from my tcp server to my tcp client. What does this mean in terms of sockets? I have been at this for awhile now and I don't see what could be wrong with my code. Its basically the same code I was using two days ago and that code worked fine. I was hoping someone could tell me what are common causes of bad file descriptors when trying to send over a socket and how I can go about checking/fixing them. Any help is appreciated. I will post some code below in case it helps.
/*Waits to connect a client. Returns true if successful*/
bool TcpServer::launchServer() {
int status;
struct addrinfo hints;
struct addrinfo *servinfo; //will point to the results
//store the connecting address and size
struct sockaddr_storage their_addr;
socklen_t their_addr_size;
memset(&hints, 0, sizeof hints); //make sure the struct is empty
hints.ai_family = AF_INET; //ipv4
hints.ai_socktype = SOCK_STREAM; //tcp
//get server info, put into servinfo
if ((status = getaddrinfo("192.168.2.3", port, &hints, &servinfo)) != 0) {
printf("\ngetaddrinfo error: %m", errno);
return false;
}
//make socket
fd = socket(servinfo->ai_family, servinfo->ai_socktype, servinfo->ai_protocol);
if (fd < 0) {
printf("\nserver socket failure %m", errno);
return false;
}
//allow reuse of port
int yes=1;
if (setsockopt(fd,SOL_SOCKET,SO_REUSEADDR,(char*) &yes,sizeof(int)) == -1) {
perror("setsockopt");
return false;
}
//bind
if(bind (fd, servinfo->ai_addr, servinfo->ai_addrlen) < 0) {
printf("\nBind error %m", errno);
return false;
}
//free up space
freeaddrinfo(servinfo);
//listen
if(listen(fd, 5) < 0) {
printf("\nListen error %m", errno);
return false;
}
their_addr_size = sizeof(their_addr);
//accept
comm_fd = accept(fd, (struct sockaddr*)&their_addr, &their_addr_size);
if( comm_fd < 0) {
printf("\nAccept error %m", errno);
return false;
}
return true;
} //END LAUNCHSERVER
void TcpServer::communicate() {
fd_set read_flags,write_flags; // the flag sets to be used
struct timeval waitd = {10, 0}; // the max wait time for an event
int sel; // holds return value for select();
int numRead; //holds return value for read()
int numSent; //holds return value for send()
char in[255]; //in buffer
char out[255]; //out buffer
//clear buffersz
memset(&in, 0, 255);
memset(&out, 0, 255);
while(!done) {
FD_ZERO(&read_flags);
FD_ZERO(&write_flags);
FD_SET(comm_fd, &read_flags);
FD_SET(comm_fd, &write_flags);
FD_SET(STDIN_FILENO, &read_flags);
FD_SET(STDIN_FILENO, &write_flags);
//call select
sel = select(comm_fd+1, &read_flags, &write_flags, (fd_set*)0, &waitd);
//if an error with select
if(sel < 0)
continue;
//if socket ready for reading
if(FD_ISSET(comm_fd, &read_flags)) {
//clear set
FD_CLR(comm_fd, &read_flags);
memset(&in, 0, 255);
numRead = recv(comm_fd, in, 255, 0);
//if an error, exit
if(numRead < 0) {
printf("\nError reading %m", errno);
myAgent->getRobot()->pauseSensorStream();
done = true;
} //end if error
//if connection closed, exit
else if(numRead == 0) {
printf("\nClosing socket");
close(comm_fd);
done = true;
} //end if connection closed
//if message, call getsendback
else if(in[0] != '\0') {
//std::cout<<"\nClient: "<<in;
getSendBack(in);
} //end if message
} //end if ready for read
//if stdin is ready for reading
if(FD_ISSET(STDIN_FILENO, &read_flags))
fgets(out, 255, stdin);
//if socket ready for writing
if(FD_ISSET(comm_fd, &write_flags)) {
//printf("\nSocket ready for write");
FD_CLR(comm_fd, &write_flags);
//check validity by checking for a digit
if(isdigit(out[0])) {
//create message to send
std::stringstream tosend;
tosend<<"# "<<out;
//std::cout<<"\ntosend: "<<tosend.str();
//send
//********ERROR HAPPENS HERE PRINTS OUT MESSAGE BELOW******
numSent = send(comm_fd, tosend.str().c_str(), tosend.str().length(), 0);
} //end if valid message
//if error, exit
if(numSent < 0) {
printf("\nError sending %m", errno);
done = true;
} //end if error
//wait for message to get there, then clear
usleep(5000);
memset(&out, 0, 255);
} //end if
} //end while
} //END COMMUNICATE
Client code is basically the same.

Your program prints "Bad file descriptor" when errno is EBADF.
From man page of send:
EBADF = An invalid descriptor was specified.
I'm quite sure that the socket is closed before the send() call.
That can happen, because program can go to "ready for writing" branch after "connection closed," branch.
Try the following:
else if(numRead == 0) {
printf("\nClosing socket");
close(comm_fd);
break;
}
Instead of:
else if(numRead == 0) {
printf("\nClosing socket");
close(comm_fd);
done = true;
}

You answered your own question. Without explicitly initializing numSent and numRead, you get garbage, which may happen to be a negative number for numSent, which would cause it to error if there was no digit in the out[] array.

Related

TCP connection fails at recv() function

I'm a newbie in socket programming.
I'm trying to interface in TCP between server and client by following a certain protocol.
After the connection is established, the communication starts by client sending a certain packet to the server. My program fails at the recv() function at client side.
Let me share you the client side of my code:
iResult = WSAStartup(MAKEWORD(2, 2), &wsaData);
if (iResult != 0)
{
printf("WSAStartup failed with error: %d\n", iResult);
return 1;
}
ZeroMemory(&hints, sizeof(hints));
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
hints.ai_protocol = IPPROTO_TCP;
iResult = getaddrinfo(LOCAL_IP, "8081", &hints, &result);
if (iResult != 0)
{
printf("getaddrinfo failed with error: %d\n", iResult);
WSACleanup();
return 1;
}
// Attempt to connect to an address until one succeeds
for (ptr = result; ptr != NULL; ptr = ptr->ai_next)
{
// Create a SOCKET for connecting to server
ConnectSocket = socket(ptr->ai_family, ptr->ai_socktype,
ptr->ai_protocol);
if (ConnectSocket == INVALID_SOCKET)
{
printf("socket failed with error: %ld\n", WSAGetLastError());
WSACleanup();
return 1;
}
// Connect to server.
iResult = connect(ConnectSocket, ptr->ai_addr, (int)ptr->ai_addrlen);
if (iResult == SOCKET_ERROR)
{
closesocket(ConnectSocket);
ConnectSocket = INVALID_SOCKET;
continue;
}
break;
}
MSG_PDDAU_INFO_PACKET* ps8ptr = new MSG_PDDAU_INFO_PACKET;
memset(ps8bufrecv, 0, DEFAULT_BUFLEN);
s32packetlen = sizeof(MSG_PDDAU_INFO_PACKET);
printf("size %d\n", sizeof(MSG_PDDAU_INFO_PACKET));
iResult = recv(ConnectSocket, ps8bufrecv, s32packetlen, 0);
if (iResult == -1)
{
printf("Here !\n");
fprintf(stderr, "recv Error Occurred %s (%d)\n", strerror(errno), errno);
return -1;
}
memcpy(ps8ptr,ps8bufrecv,sizeof(MSG_PDDAU_INFO_PACKET));
And here is the server side of the code:
nErrorStatus = WSAStartup(wVersionRequested, &wsaData);
serv_sock = socket(PF_INET, SOCK_STREAM, 0);
if(serv_sock == -1)
{
printf( "socket() Error..Error --> Code %d ", WSAGetLastError() );
error_handling("socket error");
}
memset(&serv_addr, 0, sizeof(serv_addr));
serv_addr.sin_family = PF_INET;
serv_addr.sin_addr.s_addr = inet_addr(ip);
serv_addr.sin_port = htons(CLIENT_PORT_NUMBER);
if(bind(serv_sock, (struct sockaddr*) &serv_addr, sizeof(serv_addr)) == -1)
{
printf( "bind() Error..Error --> Code %d ", WSAGetLastError() );
error_handling("bind error");
}
if(listen(serv_sock, 5) == -1)
{
printf( "listen() Error..Error --> Code %d ", WSAGetLastError() );
error_handling("listen error");
}
clnt_addr_size = sizeof(clnt_addr);
clnt_sock = accept(serv_sock, (struct sockaddr*)&clnt_addr, &clnt_addr_size);
if(clnt_sock == -1)
{
printf( "accept() Error..Error --> Code %d ", WSAGetLastError() );
error_handling("accept error");
}
MSG_PDDAU_INFO_PACKET* ps8ptr = new MSG_PDDAU_INFO_PACKET;
ps8ptr->header.msg_id = MSG_PDDAU_INFO_ID;
ps8ptr->header.msg_type = MSG_REQUEST_TYPE;
ps8ptr->time_enable = 0x01;
s32packetlen = sizeof(MSG_PDDAU_INFO_PACKET);
memset(ps8bufsend, 0, DEFAULT_BUFLEN);
memcpy(ps8bufsend,ps8ptr, s32packetlen);
iResult = send(clnt_sock, ps8bufsend, s32packetlen, 0);
if (iResult == -1)
{
fprintf(stderr, "send Error Occurred %s (%d)\n", strerror(errno), errno);
return -1;
}
The code keeps failing at the first recv/send interface after the connection, and the error message looks like below.
Server side:
Time msg id : 5
Time setting failed
Client side:
recv Error Occurred Invalid argument (22)
I don't know what's the correct way to communicate in my case.
It'd be great if anyone can point out my problem here.

Sockets using GetQueuedCompletionStatus and ERROR_MORE_DATA

I am trying to use GetQueuedCompletionStatus with winsocks, but I can't seem to get it right. The procedure is as follows:
void foo() {
...
SOCKET sck = WSASocket(AF_INET, SOCK_DGRAM, 0,
NULL, 0, WSA_FLAG_OVERLAPPED);
....
bind(sck,(struct sockaddr *)&addr,sizeof(struct sockaddr_in));
HANDLE hPort = CreateIoCompletionPort((HANDLE)sck, NULL, 0, 0 );
OVERLAPPED pOverlapped = {0,};
WSARecvFrom(sck,NULL,0,NULL,NULL,(struct sockaddr *)&laddr,&lsize,&pOverlapped,0);
BOOL bReturn = GetQueuedCompletionStatus(
hPort,
&rbytes,
(LPDWORD)&lpContext,
&pOutOverlapped,
INFINITE);
...
}
I then send some network data to the bound port from an external tool. GetQueuedCompletionStatus returns FALSE, and GetLastError() returns ERROR_MORE_DATA, which sounds correct, since I hadn't provided a buffer in WSARecvFrom.
The question is how can I provide a buffer to actually get the data from the failed I/O operation?
I tried to issue a WSARecvFrom with the original overlapped structured, but it simply queues another read, and a subsequent call to GetQueuedCompletionStatus does not return until more network data is sent.
Calling WSARecvFrom without an overlapped structure blocks it, and it also doesn't return until more network data is sent.
So, how can I handle ERROR_MORE_DATA properly, without losing the data from the first operation?
You must provide a buffer to WSARecvFrom(), just like with any read operation regardless of whether you use IOCP or not. You must ensure the buffer stays valid in memory until the IOCP operation is complete. IOCP fills the buffer you provide and then notifies the completion port when finished.
UDP cannot transfer more than 65535 bytes in a single datagram, so you can use that as your max buffer size.
In your example, your code is written to run synchronously (defeating the purpose of using IOCP at all), so you can use a local buffer:
void foo() {
...
SOCKET sck = WSASocket(AF_INET, SOCK_DGRAM, 0, NULL, 0, WSA_FLAG_OVERLAPPED);
if (sck == INVALID_SOCKET)
{
// error, do something...
return;
}
....
bind(sck,(struct sockaddr *)&addr, sizeof(struct sockaddr_in));
HANDLE hPort = CreateIoCompletionPort((HANDLE)sck, NULL, 0, 0 );
if (!hPort)
{
// error, do something...
return;
}
WSAOVERLAPPED Overlapped = {0};
Overlapped.hEvent = WSACreateEvent();
BYTE buffer[0xFFFF];
DWORD dwBytesRecvd = 0;
DWORD dwFlags = 0;
sockaddr_in fromaddr = {0};
int fromaddrlen = sizeof(fromaddr);
WSABUF buf;
buf.len = sizeof(buffer);
buf.buf = buffer;
int iRet = WSARecvFrom(sck, &buf, 1, &dwBytesRecvd, &dwFlags, (sockaddr*)&fromaddr, &fromaddrlen, &Overlapped, NULL);
if (iRet == SOCKET_ERROR)
{
if (WSAGetLastError() != WSA_IO_PENDING)
{
// error, do something...
return;
}
DWORD rBytes;
ULONG_PTR key;
LPOVERLAPPED pOverlapped = NULL;
if (!GetQueuedCompletionStatus(hPort, &rbytes, &key, &pOverlapped, INFINITE))
{
if (pOverlapped)
{
// WSARecvFrom() failed...
}
else
{
// GetQueuedCompletionStatus() failed...
}
// do something...
return;
}
}
// I/O complete, use buffer, dwBytesRecvd, dwFlags, and fromaddr as needed...
}
However, this defeats the purpose of IOCP. If you really want to be synchronous, you could just use recvfrom() instead and let it block the calling thread until data arrives. IOCP works best when you have a pool of threads servicing the completion port. Call WSARecvFrom() and let it work in the background, don't wait on it. Let a separate thread call GetQueuedCompletionPort() and process the data when it is received, eg:
struct MyOverlapped
{
WSAOVERLAPPED overlapped;
BYTE buffer[0xFFFF];
DWORD buflen;
DWORD flags;
sockaddr_storage fromaddr;
int fromaddrLen;
};
HANDLE hPort = NULL;
void foo() {
...
SOCKET sck = WSASocket(AF_INET, SOCK_DGRAM, 0, NULL, 0, WSA_FLAG_OVERLAPPED);
if (sck == INVALID_SOCKET)
{
// error, do something...
return;
}
....
bind(sck,(struct sockaddr *)&addr, sizeof(struct sockaddr_in));
hPort = CreateIoCompletionPort((HANDLE)sck, NULL, 0, 0 );
if (!hPort)
{
// error, do something...
return;
}
MyOverlapped *ov = new MyOverlapped;
ZeroMemory(ov, sizeof(*ov));
ov->overlapped.hEvent = WSACreateEvent();
ov->fromaddrlen = sizeof(ov->fromaddr);
WSABUF buf;
buf.len = sizeof(ov->buffer);
buf.buf = ov->buffer;
int iRet = WSARecvFrom(sck, &buf, 1, &ov->buflen, &ov->flags, (sockaddr*)&ov->fromaddr, &ov->fromaddrlen, (WSAOVERLAPPED*)ov, NULL);
if (iRet == SOCKET_ERROR)
{
if (WSAGetLastError() != WSA_IO_PENDING)
{
// error, do something...
return;
}
// WSARecvFrom() is now operating in the background,
// the IOCP port will be signaled when finished...
}
else
{
// data is already available,
// the IOCP port will be signaled immediately...
}
...
}
...
// in another thread...
{
...
DWORD rbytes;
ULONG_PTR key;
MyOverlapped *ov = NULL;
if (!GetQueuedCompletionStatus(hPort, &rbytes, &key, (LPOVERLAPPED*)&ov, INFINITE))
{
if (ov)
{
// WSARecvFrom() failed...
// free ov, or reuse it for another operation...
}
else
{
// GetQueuedCompletionStatus() failed...
}
}
else
{
// use ov as needed...
// free ov, or reuse it for another operation...
}
...
}

How to set SSL_connect on non blocking socket with select on linux platform

I am trying to use the select function to have non-blocking connection from a client to server.I found a tutorial with some code and tried to adapt to this:
...
sockfd = socket(AF_INET, SOCK_STREAM, 0);
err = connect(sockfd,(struct sockaddr*)&sa,sizeof(sa));
...
SSL_set_fd(pssl,sockfd);
err = SSL_connect_nonb(pssl,sockfd,60);
if(err <=0 ){
printf("SSL_connect:%s\n",ERR_error_string(SSL_get_error(pssl,err),NULL));
return -1;
}
...
The SSL_connect_nonb function is defined as bellow:
int SSL_connect_nonb(SSL*pssl,int sockfd, int nsec)
{
int flags, error;
socklen_t len;
fd_set rset, wset;
struct timeval tval;
flags = fcntl(sockfd, F_GETFL, 0);
fcntl(sockfd, F_SETFL, flags | O_NONBLOCK);
int err = SSL_connect(pssl);
int err2 = SSL_get_error(pssl,err);
switch(err2) {
default:
printf("SSL_connect err=%s\n",ERR_error_string(err2,0));
return -1;
break;
case SSL_ERROR_WANT_READ:
case SSL_ERROR_WANT_WRITE:
break;
}
FD_ZERO(&rset);
FD_ZERO(&wset);
FD_SET(sockfd, &rset);
FD_SET(sockfd, &wset);
tval.tv_sec = nsec;
tval.tv_usec = 0;
if (select(sockfd+1, &rset, &wset, NULL,nsec ? &tval:NULL) == 0) {
return -1;
}
if(FD_ISSET(sockfd,&rset) || FD_ISSET(sockfd, &wset )) {
len = sizeof(error);
if(getsockopt(sockfd, SOL_SOCKET, SO_ERROR, &error, &len) < 0){
return -1;
}
}else{
printf("sockfd not set\n");
return -1;
}
fcntl(sockfd, F_SETFL, flags);
if (error) {
return -1;
}
return 1;
}
The sockfd is correct with connect,the problem is that in SSL_connect_nonb the select function return avalue=1 (actually the condition FD_ISSET(sockfd, &wset) is successful all time),but if I use blocking method as this :
....
SSL_set_fd(pssl,sockfd);
err = SSL_connect(pssl);
if(err <=0 ){
printf("SSL_connect:%s\n",ERR_error_string(SSL_get_error(pssl,err),NULL));
return -1;
}
...
the value of err is 0 because the SSL_connect is not successful, so, how to do with SSL_connect on non blocking socket by calling select function?
SSL_connect(), aka SSL client handshake, is a complicated process, which requires several roundtrip with servers. So, when you run SSL_connect() on a non-blocking socket, it's not enough to just run it only once. When you get SSL_ERROR_WANT_READ or SSL_ERROR_WANT_WRITE, you must retry SSL_connect() again, until it succeeded or failed with other errors.

UDP Talker gives "Bad value for ai_flags" on sendto() call

I am stuck with my UDP talker app.
The goal for the moment is to initialize the server, register a client and then proceed to send something to that client.
I've worked my way through Beej's network guide and coded the following library implementation:
This inizializes the server
int init_udp_server(const char *port_string){
/** Check the input data **/
if(port_string == NULL)
port_string = DEFAULT_PORT;
/** Get the information for the server **/
memset(&addrinfo_hints, 0, sizeof addrinfo_hints);
/* Use either protocol (v4, v6) */
addrinfo_hints.ai_family = AF_UNSPEC;
/* Use UDP socket type */
addrinfo_hints.ai_socktype = SOCK_DGRAM;
/* Use system IP */
addrinfo_hints.ai_flags = AI_PASSIVE;
if( (ret = getaddrinfo(NULL, port_string, &addrinfo_hints, &addrinfo_server))
!= 0 ){
printf("Server:getaddrinfo: %s\n", gai_strerror(ret));
return -1;
}
/** Loop through the list returned by getaddrinfo and get socket **/
for( addrinfo_queue = addrinfo_server; addrinfo_queue != NULL;
addrinfo_queue = addrinfo_queue->ai_next){
if((sockfd = socket(addrinfo_queue->ai_family,
addrinfo_queue->ai_socktype, addrinfo_queue->ai_protocol)) == -1){
error("Server: get socket failed");
continue;
}
if(bind(sockfd, addrinfo_queue->ai_addr, addrinfo_queue->ai_addrlen)
== -1){
close(sockfd);
error("Server: Bind to socket error");
continue;
}
break;
}
/* If we got to addrinfo_queue == NULL, we did not get a valid socket */
if(addrinfo_queue == NULL){
error("Server: Could not bind a socket");
return -1;
}
/* We do not need the addrinfo_server anymore */
freeaddrinfo(addrinfo_server);
return 0;
}
This registers the client
int udp_server_setup_client(const char *client_addr, const char *port_string, int client_nr){
/** Check the input data **/
if(port_string == NULL)
port_string = DEFAULT_PORT;
if(client_addr == NULL){
error("No valid client list");
return -1;
}
if(client_nr < 0 || client_nr > 7){
error("No valid client Nr.");
return -1;
}
memset(&addrinfo_hints, 0, sizeof addrinfo_hints);
/* Use either protocol (v4, v6) */
addrinfo_hints.ai_family = AF_UNSPEC;
/* Use UDP socket type */
addrinfo_hints.ai_socktype = SOCK_DGRAM;
/* Get the information for the client */
if( (ret = getaddrinfo( client_addr, port_string, &addrinfo_hints,
&current)) != 0 ){
printf("Client:getaddrinfo: %s\n", gai_strerror(ret));
return -1;
}
else{
/* We read out the IP, kind of a nice check to see wheter all went fine */
char ip4[INET_ADDRSTRLEN];
struct sockaddr_in *sa = (struct sockaddr_in*) current->ai_addr;
inet_ntop(AF_INET, &(sa->sin_addr),ip4, INET_ADDRSTRLEN);
printf("Clients address: %s\n",ip4);
addrinfo_clients[client_nr] = current;
}
return 0;
}
And finally this is for writing
int udp_server_write(const char *buffer, int buffer_size, int client_nr){
/* Sanity check of the input */
if(client_nr > (MAX_NR_CLIENTS - 1) || client_nr < 0){
error("Not a valid client");
return -1;
}
if(buffer == NULL){
error("Not a valid buffer address");
return -1;
}
/* Just so we type less */
current = addrinfo_clients[client_nr];
socklen = sizeof current->ai_addr;
if((ret = sendto(sockfd, (void*)buffer, buffer_size, 0,
(sockaddr*)current->ai_addr, socklen)) == -1){
printf("Failed to send message to client %i\n", client_nr);
printf("Error Code: %s\n",gai_strerror(ret));
return -1;
}
else if(ret < buffer_size){
printf("Wrote only %i of %i bytes\n", ret, buffer_size);
return -1;
}
return ret;
}
I call the functions like this
init_udp_server("3334");
udp_server_setup_client("192.168.1.5", "3334", 0);
udp_server_write(send_buf, 256, 0);
As soon as sendto() is called I get an error:
Failed to send message to client 0
Error Code: Bad value for ai_flags
I checked it with gdb and found that the addrinfo struct is filled correctly, and the address of the client is valid.
Any one an idea where to look? I am running out of ideas...
thanks, wenzlern
When calling sendto(), the last parameter is being set to sizeof current->ai_addr, which is wrong. current->ai_addr is defined as a sockaddr* pointer, so sizeof current->ai_addr will always return 4 on a 32-bit system and 8 on a 64-bit system. It just happens that IPv4 addresses are 4 bytes in size, so sizeof current->ai_addr will only work for IPv4 addresses on 32-bit systems, but will always fail for IPv6 addresses on 32-bit systems and all addresses on 64-bit systems. You need to use current->ai_addrlen instead of sizeof.
Also, passing -1 to gai_strerror() is not valid. It expects you to pass in a real error code, such as the return value of getaddrinfo() and getnameinfo(). sendto() does not return an actual error code. When it fails, you have to use WSAGetLastError() on Windows or errno on other systems to get the actual error code.
Try this:
if ((ret = sendto(sockfd, (char*)buffer, buffer_size, 0, (sockaddr*)current->ai_addr, current->ai_addrlen)) == -1)
{
#ifdef _WIN32
ret = WSAGetLastError();
#else
ret = errno;
#endif
printf("Failed to send message to client %i\n", client_nr);
printf("Error Code: (%d) %s\n", ret, gai_strerror(ret));
return -1;
}

Reciving UDP packets on iPhone

I'm trying to establish UDP communication between a MAC OS and an iPod through Wi-Fi, at this point I'm able to send packets from the iPod and I can see those packets have the right MAC and ip addresses (I'm using wireshark to monitor the network) but the MAC receives the packets only when the wireshark is on, otherwise recvfrom() returns -1.
When I try to transmit from MAC to iPhone I have the same result, I can see the packets are sent but the iPhone doesn't seem to get them.
I'm using the next code to send:
struct addrinfo hints;
int rv;
memset(&hints, 0, sizeof hints);
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_DGRAM;
if ((rv = getaddrinfo(IP, SERVERPORT, &hints, &servinfo)) != 0) {
fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(rv));
return 1;
}
// loop through all the results and make a socket
for(p = servinfo; p != NULL; p = p->ai_next) {
if ((sockfd = socket(p->ai_family, p->ai_socktype, p->ai_protocol)) == -1) {
perror("talker: socket");
continue;
}
break;
}
if (p == NULL) {
fprintf(stderr, "talker: failed to bind socket\n");
return 2;
}
while (cond)
sntBytes += sendto(sockfd, message, strlen(message), 0, p->ai_addr, p->ai_addrlen);
return 0;
and this code to receive:
struct addrinfo hints, *p;
int rv;
memset(&hints, 0, sizeof hints);
hints.ai_family = AF_UNSPEC; // set
hints.ai_socktype = SOCK_DGRAM;
hints.ai_flags = AI_PASSIVE; // use to AF_INET to force IPv4 my IP
if ((rv = getaddrinfo(NULL, MYPORT, &hints, &servinfo)) != 0) {
fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(rv));
return 1;
}
// loop through all the results and bind to the first we can
for(p = servinfo; p != NULL; p = p->ai_next) {
if ((sockfd = socket(p->ai_family, p->ai_socktype, p->ai_protocol)) == -1) {
perror("listener: socket");
continue;
}
if (bind(sockfd, p->ai_addr, p->ai_addrlen) == -1) {
close(sockfd);
perror("listener: bind");
continue;
}
break;
}
if (p == NULL) {
fprintf(stderr, "listener: failed to bind socket\n");
return 2;
}
addr_len = sizeof their_addr;
fcntl(sockfd, F_SETFL,O_NONBLOCK);
int rcvbuf_size = 128 * 1024; // That's 128Kb of buffer space.
setsockopt(sockfd, SOL_SOCKET, SO_RCVBUF,
&rcvbuf_size, sizeof(rcvbuf_size));
printf("listener: waiting to recvfrom...\n");
while (cond)
rcvBytes = recvfrom(sockfd, buf, MAXBUFLEN-1 , 0, (struct sockaddr *)&their_addr, &addr_len);
return 0;
What am I missing?
It would be good to get some more information about the length of data you are sending.
I will assume you are trying to send an ASCII string.
Also, this appears to be either never called or an infinite send loop:
while (cond)
sntBytes += sendto(sockfd, message, strlen(message), 0, p->ai_addr, p->ai_addrlen);
You might want to use code that actually includes some error checking:
Send String
int sendResult = send( connectedSocket, stringBuffer, stringLength, 0 );
if (sendResult == -1) {
perror("Error while trying to send string!");
}
else {
NSLog(#"String '%s' sent successfully", stringBuffer );
}
Receive String
memset( ReceiveBuffer, '\0', sizeof(ReceiveBuffer) );
int receiveResult = recv( connectedSocket, ReceiveBuffer, sizeof(ReceiveBuffer), 0);
if ( receiveResult == -1 ) {
perror("recv");
}
else {
NSLog(#"String received successfully: '%s'", ReceiveBuffer );
}