source: Daodan/Flatline/src/Flatline.c@ 457

Last change on this file since 457 was 457, checked in by rossy, 15 years ago

Flatline

File size: 2.4 KB
Line 
1#include "Flatline.h"
2
3bool Net_Listen(uint16_t port, bool (*packet_callback)(char* data, int datalen, int from))
4{
5 int sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
6
7 if (sock < 0)
8 {
9 DDrStartupMessage("could not create socket");
10 return false;
11 }
12
13 sockaddr_in address;
14 memset(&address, 0, sizeof(sockaddr_in));
15 address.sin_family = AF_INET;
16 address.sin_addr.s_addr = htonl(INADDR_ANY);
17 address.sin_port = htons(port);
18
19 if (bind(sock, (sockaddr*)&address, sizeof(sockaddr_in)) < 0)
20 {
21 DDrStartupMessage("could not bind port %d", port);
22 closesocket(sock);
23 return false;
24 }
25
26 char data[65537];
27 data[sizeof(data) - 1] = '\0';
28 sockaddr_in from;
29 int recvlen;
30 for (;;)
31 {
32 int fromlen = sizeof(sockaddr_in);
33 memset(&from, 0, sizeof(sockaddr_in));
34 recvlen = recvfrom(sock, data, sizeof(data) - 1, 0, (sockaddr*)&from, (void*)&fromlen);
35 if (!packet_callback(data, recvlen, ntohl(from.sin_addr.s_addr)))
36 break;
37 }
38 closesocket(sock);
39 return true;
40}
41
42int Net_CreateSocket(uint16_t port)
43{
44 int sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
45
46 if (sock < 0)
47 {
48 DDrStartupMessage("could not create socket");
49 return -1;
50 }
51
52 sockaddr_in address;
53 memset(&address, 0, sizeof(sockaddr_in));
54 address.sin_family = AF_INET;
55 address.sin_addr.s_addr = htonl(INADDR_ANY);
56 address.sin_port = htons(port);
57
58 if (bind(sock, (sockaddr*)&address, sizeof(sockaddr_in)) < 0)
59 {
60 DDrStartupMessage("could not bind port %d", port);
61 return false;
62 }
63
64 unsigned long nonBlocking = 1;
65 if (ioctlsocket(sock, FIONBIO, &nonBlocking))
66 {
67 DDrStartupMessage("failed to set non-blocking socket");
68 return false;
69 }
70
71 return sock;
72}
73
74bool Net_Send(int socket, int ip, uint16_t port, char* data, int datalen)
75{
76 sockaddr_in address;
77 memset(&address, 0, sizeof(sockaddr_in));
78 address.sin_family = AF_INET;
79 address.sin_addr.s_addr = ip;
80 address.sin_port = htons(port);
81
82 return sendto(socket, data, datalen, 0, (sockaddr*)&address, sizeof(address));
83}
84
85void Net_CloseSocket(int sock)
86{
87 closesocket(sock);
88}
89
90bool FLrListen_PacketCallback(char* data, int datalen, int from)
91{
92 static int recieved = 0;
93
94 data[datalen] = '\0';
95 if (!strcmp(data, "hi"))
96 printf("\r%d packets recieved ", ++recieved);
97 return true;
98}
99
100bool FLrListen_Run()
101{
102 return Net_Listen(27777, FLrListen_PacketCallback);
103}
Note: See TracBrowser for help on using the repository browser.