-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathReceiverSocket.c
84 lines (62 loc) · 1.71 KB
/
ReceiverSocket.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
/*
* SenderSocket.c
*
* Created on: Mar 14, 2010
* Author: lucas
*/
#include "ReceiverSocket.h"
#define BUFFER_SIZE 1024
struct ReceiverSocket
{
int handle;
};
ReceiverSocket* createReceiverSocket(unsigned short port)
{
ReceiverSocket* receiverSocket = (ReceiverSocket*)malloc(sizeof(ReceiverSocket));
receiverSocket->handle = socket( AF_INET, SOCK_DGRAM, IPPROTO_UDP );
if ( receiverSocket->handle <= 0 )
{
printf( "failed to create socket\n" );
return NULL;
}
struct sockaddr_in tempAddress;
tempAddress.sin_family = AF_INET;
tempAddress.sin_addr.s_addr = INADDR_ANY;
tempAddress.sin_port = htons( port );
if ( bind( receiverSocket->handle, (struct sockaddr*) &tempAddress, sizeof(struct sockaddr_in) ) < 0 )
{
printf( "failed to bind socket\n" );
return NULL;
}
int nonBlocking = 1;
if ( fcntl( receiverSocket->handle, F_SETFL, O_NONBLOCK, nonBlocking ) == -1 )
{
printf( "failed to set non-blocking socket\n" );
return NULL;
}
return receiverSocket;
}
int receivePacket(ReceiverSocket* receiverSocket, unsigned char* packetData, int maximumPacketSize, unsigned int* ipAddress, unsigned short* port)
{
struct sockaddr_in from;
socklen_t fromLength = sizeof( from );
int receivedBytes = recvfrom( receiverSocket->handle, (char*)packetData, maximumPacketSize,
0, (struct sockaddr*)&from, &fromLength );
if ( receivedBytes > 0 )
{
//*ipAddress = ntohl( from.sin_addr.s_addr );
//*port = ntohs( from.sin_port );
*ipAddress = ( from.sin_addr.s_addr );
*port = ( from.sin_port );
}
else
{
//printf("No packet received\n");
}
return receivedBytes;
// process received packet
}
void deleteReceiverSocket(ReceiverSocket* receiverSocket)
{
free(receiverSocket);
}