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 #include "socket.h"
30
31 #include <unistd.h>
32 #include <sys/fcntl.h>
33 #include <sys/socket.h>
34 #include <netinet/in.h>
35 #include <arpa/inet.h>
36
37 int util_server_socket_local(
short *port) {
38 int socket_fd = socket(
AF_INET,
SOCK_STREAM,
0);
39 if(socket_fd <
0) {
40 return -1;
41 }
42
43 short socket_port =
0;
44 if(port) {
45 socket_port = *port;
46 }
47
48 struct sockaddr_in addr;
49 addr.sin_family =
AF_INET;
50 addr.sin_addr.s_addr = htonl(
INADDR_LOOPBACK);
51 addr.sin_port = htons(socket_port);
52
53 if(bind(socket_fd, (
struct sockaddr*)&addr,
sizeof(addr))) {
54 close(socket_fd);
55 return -1;
56 }
57
58 socklen_t len =
sizeof(addr);
59 if(getsockname(socket_fd, (
struct sockaddr *)&addr, &len) <
0) {
60 close(socket_fd);
61 return -1;
62 }
63
64 if(port) {
65 *port = ntohs(addr.sin_port);
66 }
67
68 return socket_fd;
69 }
70
71 int util_socket_connect_local(
short port) {
72 int fd = socket(
AF_INET,
SOCK_STREAM,
0);
73 if(fd <
0) {
74 return -1;
75 }
76
77 struct sockaddr_in addr;
78 addr.sin_family =
AF_INET;
79 addr.sin_addr.s_addr = htonl(
INADDR_LOOPBACK);
80 addr.sin_port = htons(port);
81
82 if(connect(fd, (
struct sockaddr*)&addr,
sizeof(addr))) {
83 close(fd);
84 return -1;
85 }
86
87 return fd;
88 }
89
90 int util_socketpair(
int fds[
2]) {
91 if (socketpair(
AF_UNIX,
SOCK_STREAM,
0, fds)) {
92 fds[
0] =
-1;
93 fds[
1] =
-1;
94 return -1;
95 }
96 return 0;
97 }
98
99 int util_socket_setnonblock(
int fd,
int nonblock) {
100 int flags;
101 if ((flags = fcntl(fd,
F_GETFL,
0)) ==
-1) {
102 flags =
0;
103 }
104 if(nonblock) {
105 flags |=
O_NONBLOCK;
106 }
else {
107 flags &= ~
O_NONBLOCK;
108 }
109 if (fcntl(fd,
F_SETFL, flags) !=
0) {
110 return 1;
111 }
112 return 0;
113 }
114