udp.cpp
Go to the documentation of this file.
00001 #include <sys/time.h>
00002 #include <arpa/inet.h>
00003 #include <stdio.h>
00004 #include <sys/types.h>
00005 #include <sys/socket.h>
00006 #include <unistd.h>
00007 #include <stdlib.h>
00008 #include <string.h>
00009 #include <fcntl.h>
00010 #include "udp.h"
00011 
00012 int udpClient_Init(udp_struct *udp, const char* host, int port)
00013 {
00014   udp->slen=sizeof(udp->si_other);
00015   
00016   if ((udp->s=socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP))==-1) return 1;
00017   
00018   memset((char *) &udp->si_other, 0, sizeof(udp->si_other));
00019   udp->si_other.sin_family = AF_INET;
00020   udp->si_other.sin_port = htons(port);
00021   if (inet_aton(host, &udp->si_other.sin_addr)==0) return 2;
00022 
00023   return 0;
00024 }
00025 
00026 int udpClient_Send(udp_struct *udp, char* buf, int len)
00027 {  
00028   if (sendto(udp->s, buf, len, 0, (const sockaddr*)&udp->si_other, udp->slen)==-1) return 1;
00029   return 0;
00030 }
00031 
00032 
00033 
00034 void udpClient_Close(udp_struct *udp)
00035 {  
00036   close(udp->s);
00037 }
00038 
00039 
00040 int udpServer_Init(udp_struct *udp, int port, int blocking)
00041 {
00042   udp->slen=sizeof(udp->si_other);
00043  
00044   if ((udp->s=socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP))==-1) return 1;
00045  
00046   if(blocking==0) { 
00047     // Set socket to be non-blocking.  All of the sockets for    
00048     // the incoming connections will also be non-blocking since  
00049     // they will inherit that state from the listening socket.   
00050     int x;
00051     x = fcntl(udp->s, F_GETFL, 0);
00052     fcntl(udp->s, F_SETFL, x | O_NONBLOCK);
00053   }
00054  
00055   //Bind the socket  
00056   memset((char *) &udp->si_me, 0, sizeof(udp->si_me));
00057   udp->si_me.sin_family = AF_INET;
00058   udp->si_me.sin_port = htons(port);
00059   udp->si_me.sin_addr.s_addr = htonl(INADDR_ANY);
00060   if (bind(udp->s, (const sockaddr*)&udp->si_me, sizeof(udp->si_me))==-1) return 3;
00061 
00062   return 0;
00063 }
00064 
00065 //returns size of packet received or returns -1 and errno=EWOULDBLOCK if no data available
00066 int udpServer_Receive(udp_struct *udp, char* buf, int len)  
00067 {
00068   return recvfrom(udp->s, buf, len, 0, (sockaddr*)&udp->si_other, &udp->slen);
00069 }
00070   
00071 void udpServer_Close(udp_struct *udp)
00072 {  
00073   close(udp->s);
00074 }


ardrone2islab
Author(s): Trung Nguyen , Oscar De Silva
autogenerated on Thu Jun 6 2019 20:53:51