-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsocket.c
96 lines (71 loc) · 1.92 KB
/
socket.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
84
85
86
87
88
89
90
91
92
93
94
95
96
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/time.h>
#include <time.h>
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include "output.h"
#include "simplebuffer.h"
void socket_close(int sock) {
close(sock);
}
int socket_open(char *laddr, int port) {
struct sockaddr_in lsin;
int sock;
memset(&lsin, 0, sizeof(struct sockaddr_in));
sock=socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP);
if (sock<0)
return sock;
lsin.sin_family=AF_INET;
lsin.sin_addr.s_addr=INADDR_ANY;
if (laddr)
inet_aton(laddr, &lsin.sin_addr);
lsin.sin_port=htons(port);
if (bind(sock, (struct sockaddr *) &lsin,
sizeof(struct sockaddr_in)) != 0) {
close(sock);
return -1;
}
return sock;
}
int socket_set_nonblock(int sock) {
unsigned int flags;
flags=fcntl(sock, F_GETFL);
return fcntl(sock, F_SETFL, flags | O_NONBLOCK);
}
int socket_set_ttl(int sock, int ttl) {
if (ttl)
return setsockopt(sock, IPPROTO_IP, IP_MULTICAST_TTL, &ttl, sizeof(ttl));
return 0;
}
/* Join the socket on a multicats group e.g. tell the kernel
* to send out IGMP join messages ...
*
* Returns 0 on success and != 0 in failure
*
*/
int socket_join_multicast(int sock, char *addr) {
struct ip_mreq mreq;
memset(&mreq, 0, sizeof(struct ip_mreq));
/* Its not an ip address ? */
if (!inet_aton(addr, &mreq.imr_multiaddr))
return -1;
if (!IN_MULTICAST(ntohl(mreq.imr_multiaddr.s_addr)))
return 0;
mreq.imr_interface.s_addr=INADDR_ANY;
return setsockopt(sock, IPPROTO_IP, IP_ADD_MEMBERSHIP, &mreq, sizeof(mreq));
}
int socket_connect(int sock, char *addr, int port) {
struct sockaddr_in rsin;
memset(&rsin, 0, sizeof(struct sockaddr_in));
/* Create remote end sockaddr_in */
rsin.sin_family=AF_INET;
rsin.sin_port=htons(port);
rsin.sin_addr.s_addr=INADDR_ANY;
if (addr)
inet_aton(addr, &rsin.sin_addr);
return connect(sock, (struct sockaddr *) &rsin, sizeof(struct sockaddr_in));
}