5 #define IP_LISTENER_BACKLOG 511 /* So if it gets masked by 256 or some other
6 such value it'll still be respectable */
8 /* Any IP-related initialisations. For now, this means blocking SIGPIPE */
9 int ip_initialise(void)
13 sa
.sa_handler
= SIG_IGN
;
15 sigemptyset(&sa
.sa_mask
);
16 if(sigaction(SIGPIPE
, &sa
, NULL
) != 0)
21 int ip_create_listener_split(const char *ip
, unsigned short port
)
23 struct sockaddr_in in_addr
;
27 /* Create the socket */
28 if((fd
= socket(PF_INET
, SOCK_STREAM
, 0)) == -1)
30 /* Set the SO_REUSEADDR flag - servers act weird without it */
31 if(setsockopt(fd
, SOL_SOCKET
, SO_REUSEADDR
, (char *)(&reuseVal
),
32 sizeof(reuseVal
)) != 0)
34 /* Prepare the listen address stuff */
35 in_addr
.sin_family
= AF_INET
;
36 memcpy(&in_addr
.sin_addr
.s_addr
, ip
, 4);
37 in_addr
.sin_port
= htons(port
);
38 /* Bind to the required port/address/interface */
39 if(bind(fd
, (struct sockaddr
*)&in_addr
, sizeof(struct sockaddr_in
)) != 0)
41 /* Start "listening" */
42 if(listen(fd
, IP_LISTENER_BACKLOG
) != 0)
51 int ip_create_connection_split(const char *ip
, unsigned short port
)
53 struct sockaddr_in in_addr
;
56 /* Create the socket */
57 if((fd
= socket(PF_INET
, SOCK_STREAM
, 0)) == -1)
59 /* Make it non-blocking */
60 if(((flags
= fcntl(fd
, F_GETFL
, 0)) < 0) ||
61 (fcntl(fd
, F_SETFL
, flags
| O_NONBLOCK
) < 0))
63 /* Prepare the connection address stuff */
64 in_addr
.sin_family
= AF_INET
;
65 memcpy(&in_addr
.sin_addr
.s_addr
, ip
, 4);
66 in_addr
.sin_port
= htons(port
);
67 /* Start a connect (non-blocking, in all likelihood) */
68 if((connect(fd
, (struct sockaddr
*)&in_addr
,
69 sizeof(struct sockaddr_in
)) != 0) &&
70 (errno
!= EINPROGRESS
))
79 static char all_local_ip
[] = {0x00,0x00,0x00,0x00};
81 int ip_parse_address(const char *address
, const char **parsed_ip
,
82 unsigned short *parsed_port
, int accept_all_ip
)
85 struct hostent
*lookup
;
87 const char *ptr
= strstr(address
, ":");
88 const char *ip
= all_local_ip
;
91 /* We assume we're listening on all local interfaces and have
92 * only specified a port. */
98 if((ptr
- address
) > 255)
101 memcpy(buf
, address
, ptr
- address
);
103 if((lookup
= gethostbyname(buf
)) == NULL
) {
104 /* Spit a message to differentiate between lookup failures and
106 fprintf(stderr
, "hostname lookup for '%s' failed\n", buf
);
109 ip
= lookup
->h_addr_list
[0];
113 if(!int_strtoul(ptr
, &port
) || (port
> 65535))
116 *parsed_port
= (unsigned short)port
;
120 int ip_create_listener(const char *address
)
125 if(!ip_parse_address(address
, &ip
, &port
, 1))
127 return ip_create_listener_split(ip
, port
);
130 int ip_create_connection(const char *address
)
135 if(!ip_parse_address(address
, &ip
, &port
, 0))
137 return ip_create_connection_split(ip
, port
);
140 int ip_accept_connection(int listen_fd
)
142 return accept(listen_fd
, NULL
, NULL
);
145 #endif /* !defined(NO_IP) */