1 #include "syshdrs.h"
2
3 int
SBind(int sockfd,const int port,const int nTries,const int reuseFlag)4 SBind(int sockfd, const int port, const int nTries, const int reuseFlag)
5 {
6 unsigned int i;
7 int on;
8 int onsize;
9 struct sockaddr_in localAddr;
10
11 localAddr.sin_family = AF_INET;
12 localAddr.sin_addr.s_addr = htonl(INADDR_ANY);
13 localAddr.sin_port = htons((unsigned short) port);
14
15 if (reuseFlag != kReUseAddrNo) {
16 /* This is mostly so you can quit the server and re-run it
17 * again right away. If you don't do this, the OS may complain
18 * that the address is still in use.
19 */
20 on = 1;
21 onsize = (int) sizeof(on);
22 (void) setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR,
23 (char *) &on, onsize);
24
25 #ifdef SO_REUSEPORT
26 /* Tells kernel that it's okay to have more
27 * than one process originating from this
28 * local port.
29 */
30 on = 1;
31 onsize = (int) sizeof(on);
32 (void) setsockopt(sockfd, SOL_SOCKET, SO_REUSEPORT,
33 (char *) &on, onsize);
34 #endif /* SO_REUSEPORT */
35 }
36
37 for (i=1; ; i++) {
38 /* Try binding a few times, in case we get Address in Use
39 * errors.
40 */
41 if (bind(sockfd, (struct sockaddr *) &localAddr, sizeof(struct sockaddr_in)) == 0) {
42 break;
43 }
44 if ((int) i == nTries) {
45 return (-1);
46 }
47 /* Give the OS time to clean up the old socket,
48 * and then try again.
49 */
50 sleep(i * 3);
51 }
52
53 return (0);
54 } /* SBind */
55
56
57
58
59 int
SListen(int sfd,int backlog)60 SListen(int sfd, int backlog)
61 {
62 return (listen(sfd, (unsigned int) backlog));
63 } /* SListen */
64