3 * serveraccept - accept a server connection on named port
5 * Copyright © 1994 AmiTCP/IP Group,
6 * Network Solutions Development Inc.
8 * Copyright © 2005 Pavel Fedin
11 /****** net.lib/serveraccept ***********************************************
14 serveraccept - Accept a server connection on named port
17 socket = serveraccept(name, peer);
19 long serveraccept(char *, struct sockaddr_in *);
22 The serveraccept() library call binds a socket to the named Internet
23 TCP port. Then it listens the socket and accepts the connection to
24 the port. The peer's socket address is returned in sockaddr pointed
27 The port name is resolved by getservbyname() call. A numeric value
28 for port name is also accepted.
30 This module is meant for daemon developing.
33 name - port name or numeric string.
34 peer - pointer to struct sockaddr_in
37 socket - positive socket id for success or -1 for failure.
39 peer - sockaddr_in structure containing peer's internet address.
40 Note that on error, the structure containing peer address
41 is not necessarily updated.
44 bsdsocket/accept, bsdsocket/getservbyname
46 *****************************************************************************
51 #include <clib/netlib_protos.h>
52 #include <proto/socket.h>
53 #include <proto/dos.h>
59 #include <sys/param.h>
60 #include <sys/socket.h>
61 #include <netinet/in.h>
73 * Accept a server socket from the named port
76 serveraccept(char *pname
, struct sockaddr_in
*ha
)
78 struct sockaddr_in sin
;
79 socklen_t ha_len
= sizeof(*ha
);
85 /* Create address corresponding our service */
86 bzero((caddr_t
)&sin
, sizeof(sin
));
87 sin
.sin_len
= sizeof(struct sockaddr_in
);
88 sin
.sin_family
= AF_INET
;
90 /* A port must be in the range 1 - 65535 */
91 if (StrToLong(pname
, &port
) > 0 && port
< 65536 )
93 else if (sp
= getservbyname(pname
, "tcp"))
94 sin
.sin_port
= sp
->s_port
;
99 sin
.sin_addr
.s_addr
= INADDR_ANY
;
101 if ((s
= socket(AF_INET
, SOCK_STREAM
, 0)) < 0) {
102 PrintNetFault(Errno(), "socket");
106 /* Reuse this port */
107 if (setsockopt(s
, SOL_SOCKET
, SO_REUSEADDR
, (char *)&on
, sizeof(on
)) < 0) {
108 PrintNetFault(Errno(), "setsockopt");
109 sa
= -1; goto Return
;
112 /* Bind it to socket */
113 if (bind(s
, (struct sockaddr
*)&sin
, sizeof(sin
)) < 0 ) {
114 PrintNetFault(Errno(), "bind");
115 sa
= -1; goto Return
;
118 if (listen(s
, 1) < 0) {
119 PrintNetFault(Errno(), "listen");
120 sa
= -1; goto Return
;
123 if ((sa
= accept(s
, (struct sockaddr
*)ha
, &ha_len
)) < 0){
124 PrintNetFault(Errno(), "accept");