Reciving UDP packets on iPhone - 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 );
}

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.

Why is the client's file descriptor used while calling the recv and send funtions on both server and client sides?

TCPServer
#include<stdio.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<netinet/ip.h>
#include<netinet/in.h>
#include<string.h>
#include<stdlib.h>
int main()
{
int fd = socket(AF_INET, SOCK_STREAM, 0);
if(fd == -1)
{
printf("socket failed!\n");
exit(0);
}
printf("Enter port: ");
int port;
scanf("%d",&port);
struct sockaddr_in server;
server.sin_family = AF_INET;
server.sin_port = htons(port);
server.sin_addr.s_addr = INADDR_ANY;
int bind_ret = bind(fd, (struct sockaddr*)(&server), sizeof(server));
if(bind_ret == -1)
{
printf("bind failed!\n");
exit(0);
}
int listen_ret = listen(fd, 10);
if(listen_ret == -1)
{
printf("listen failed!\n");
exit(0);
}
struct sockaddr_in client;
int l = sizeof(client);
int client_fd = accept(fd, (struct sockaddr*)(&client), &l);
if(client_fd == -1)
{
printf("accept failed!\n");
exit(0);
}
while(1)
{
char msg_recv[50];
int recv_ret = recv(client_fd, msg_recv, sizeof(msg_recv),0);
if(recv_ret == -1)
{
printf("recv failed!\n");
exit(0);
}
msg_recv[recv_ret]='\0';
if(strcmp("bye",msg_recv)==0)
{
exit(0);
}
printf("Message recieved: %s\n",msg_recv);
char msg_send[50];
printf("Enter message: ");
scanf(" %s",msg_send);
int send_ret = send(client_fd, msg_send, strlen(msg_send),0);
if(send_ret == 0)
{
printf("send failed!\n");
}
if(strcmp("bye",msg_send) == 0)
exit(0);
}
}
TCPClient
#include<stdio.h>
#include<sys/socket.h>
#include<sys/types.h>
#include<netinet/ip.h>
#include<netinet/in.h>
#include<string.h>
#include<stdlib.h>
int main()
{ int fd = socket(AF_INET, SOCK_STREAM, 0);
if(fd == -1)
{
printf("socket failed!\n");
exit(0);
}
int port;
printf("Enter port number: ");
scanf("%d",&port);
struct sockaddr_in client;
client.sin_family = AF_INET;
client.sin_port = htons(port);
client.sin_addr.s_addr = INADDR_ANY;
int connect_ret = connect(fd, (struct sockaddr*)(&client), sizeof(client));
if(connect_ret == -1)
{
printf("connect failed!\n");
exit(0);
}
while(1)
{
printf("Enter message: ");
char msg_send[50];
scanf("%s",msg_send);
int send_ret = send(fd, msg_send, strlen(msg_send), 0);
if(send_ret == -1)
{
printf("send failed!\n");
exit(0);
}
if(strcmp("bye", msg_send)==0)
{
exit(0);
}
char msg_recv[50];
int recv_ret = recv(fd, msg_recv, sizeof(msg_recv), 0);
if(recv_ret == -1)
{
printf("recv failed!\n");
exit(0);
}
msg_recv[recv_ret]= '\0';
if(strcmp("bye", msg_recv) == 0)
exit(0);
printf("Message recieved: %s \n",msg_recv);
}
}
In the above program for Server, recv and send were called by passing client_fd as the argument, while in the program for Client, recv and send were called by passing fd as the argument. I wanted to know why on the server side we did not use its own socket file descriptor like we did on the client side?
The server’s fd descriptor is a listen()’ing socket. It can’t perform any I/O, only receive incoming client connections. accept() pulls a pending client connection from fd’s queue and returns a new socket descriptor that can perform I/O with that client.
The client’s fd descriptor is a connect()‘ing socket. It can perform I/O with the server once its connection has been accepted.

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;
}

Why does bind return the same ephemeral port?

I have a problem where I create two UDP sockets, bind them to the loopback address with port 0 (requesting the stack to assign an ephemeral port). My understanding is that both sockets should be on different ports. In the code example below, both sockets are reported to be on the same IP address and port.
#include <stdio.h>
#include <arpa/inet.h>
int main(int, char**)
{
int fd1 = ::socket(AF_INET, SOCK_DGRAM, 0);
if (fd1 < 0)
{
perror("fd1 socket()");
return -1;
}
int fd2 = ::socket(AF_INET, SOCK_DGRAM, 0);
if (fd2 < 0)
{
perror("fd2 socket()");
return -1;
}
// Set SO_REUSEADDR for both sockets
int reuse = 1;
if (::setsockopt(fd1, SOL_SOCKET, SO_REUSEADDR, &reuse, sizeof(reuse)) < 0)
{
perror("fd1 SO_REUSEADDR failed");
return -1;
}
if (::setsockopt(fd2, SOL_SOCKET, SO_REUSEADDR, &reuse, sizeof(reuse)) < 0)
{
perror("fd2 SO_REUSEADDR failed");
return -1;
}
sockaddr_storage storage;
socklen_t addrlen = sizeof(storage);
sockaddr_in& addr = reinterpret_cast<sockaddr_in&>(storage);
addr.sin_family = AF_INET;
addr.sin_port = 1234;
addr.sin_port = 0;
if (::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr) <= 0)
{
perror("Failed to create address 127.0.0.1");
return -1;
}
sockaddr* pAddr = reinterpret_cast<sockaddr*>(&storage);
if (::bind(fd1, pAddr, addrlen) < 0)
{
perror("bind fd1 failed");
return -1;
}
// Get the local address for fd1
addrlen = sizeof(storage);
if (::getsockname(fd1, pAddr, &addrlen))
{
perror("getsockname for fd1 failed");
return -1;
}
char straddr[INET_ADDRSTRLEN];
if (!inet_ntop(AF_INET, &addr.sin_addr, straddr, sizeof(straddr)))
{
perror("inet_ntop for fd1 failed");
return -1;
}
printf("fd1=%d addr=%s:%d\n", fd1, straddr, addr.sin_port);
if (::bind(fd2, pAddr, addrlen) < 0)
{
perror("bind fd2 failed");
return -1;
}
// Get the local address for fd2
addrlen = sizeof(storage);
if (::getsockname(fd2, pAddr, &addrlen))
{
perror("getsockname for fd2 failed");
return -1;
}
if (!inet_ntop(AF_INET, &addr.sin_addr, straddr, sizeof(straddr)))
{
perror("inet_ntop for fd2 failed");
return -1;
}
printf("fd2=%d addr=%s:%d\n", fd2, straddr, addr.sin_port);
return 0;
}
This code gives the following output ...
fd1=4 addr=127.0.0.1:1933
fd2=5 addr=127.0.0.1:1933
I need both sockets on the same (local) IP address, but different ports. Can anyone explain why both sockets share the same port? Can anyone suggest a fix?
That is the expected behavior for SO_REUSEADDR on a UDP socket. Remove that setting to return to normal allocation rules.