1 /* Copyright (C) 2002 Free Software Foundation, Inc.
2 This file is part of the GNU C Library.
4 The GNU C Library is free software; you can redistribute it and/or
5 modify it under the terms of the GNU Lesser General Public
6 License as published by the Free Software Foundation; either
7 version 2.1 of the License, or (at your option) any later version.
9 The GNU C Library is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12 Lesser General Public License for more details.
14 You should have received a copy of the GNU Lesser General Public
15 License along with the GNU C Library; if not, write to the Free
16 Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
27 #include <sys/socket.h>
32 static int svc_socket (u_long number, int type, int protocol, int port, int reuse)
34 struct sockaddr_in addr;
35 char rpcdata [1024], servdata [1024];
36 struct rpcent rpcbuf, *rpcp = NULL;
37 struct servent servbuf, *servp = NULL;
39 const char *proto = protocol == IPPROTO_TCP ? "tcp" : "udp";
41 if ((sock = socket (AF_INET, type, protocol)) < 0) {
42 errstr(_("Cannot create socket: %s\n"), strerror(errno));
48 if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &ret, sizeof(ret)) < 0) {
49 errstr(_("Cannot set socket options: %s\n"), strerror(errno));
54 memset(&addr, 0, sizeof(addr));
55 addr.sin_family = AF_INET;
58 ret = getrpcbynumber_r(number, &rpcbuf, rpcdata, sizeof(rpcdata), &rpcp);
59 if (ret == 0 && rpcp != NULL) {
61 ret = getservbyname_r(rpcp->r_name, proto, &servbuf, servdata,
62 sizeof servdata, &servp);
63 if ((ret != 0 || servp == NULL) && rpcp->r_aliases) {
66 /* Then we try aliases. */
67 for (a = (const char **) rpcp->r_aliases; *a != NULL; a++) {
68 ret = getservbyname_r(*a, proto, &servbuf, servdata,
69 sizeof servdata, &servp);
70 if (ret == 0 && servp != NULL)
74 if (ret == 0 && servp != NULL)
83 if (bind(sock, (struct sockaddr *) &addr, sizeof(struct sockaddr_in)) < 0) {
84 errstr(_("Cannot bind to given address: %s\n"), strerror(errno));
90 /* Service not found? */
99 * Create and bind a TCP socket based on program number
101 int svctcp_socket(u_long number, int port, int reuse)
103 return svc_socket(number, SOCK_STREAM, IPPROTO_TCP, port, reuse);
107 * Create and bind a UDP socket based on program number
109 int svcudp_socket(u_long number, int port, int reuse)
111 return svc_socket(number, SOCK_DGRAM, IPPROTO_UDP, port, reuse);