Imported from ../bash-2.05b.tar.gz.
[platform/upstream/bash.git] / lib / sh / netconn.c
1 /* netconn.c -- is a particular file descriptor a network connection?. */
2
3 /* Copyright (C) 2002 Free Software Foundation, Inc.
4
5    This file is part of GNU Bash, the Bourne Again SHell.
6
7    Bash is free software; you can redistribute it and/or modify it
8    under the terms of the GNU General Public License as published by
9    the Free Software Foundation; either version 2, or (at your option)
10    any later version.
11
12    Bash is distributed in the hope that it will be useful, but WITHOUT
13    ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
14    or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public
15    License for more details.
16
17    You should have received a copy of the GNU General Public License
18    along with Bash; see the file COPYING.  If not, write to the Free
19    Software Foundation, 59 Temple Place, Suite 330, Boston, MA 02111 USA.
20 */
21
22 #include <config.h>
23
24 #include <bashtypes.h>
25 #ifndef _MINIX
26 #  include <sys/file.h>
27 #endif
28 #include <posixstat.h>
29 #include <filecntl.h>
30
31 #include <errno.h>
32
33 #if defined (HAVE_UNISTD_H)
34 #  include <unistd.h>
35 #endif
36
37 /* The second and subsequent conditions must match those used to decide
38    whether or not to call getpeername() in isnetconn(). */
39 #if defined (HAVE_SYS_SOCKET_H) && defined (HAVE_GETPEERNAME) && !defined (SVR4_2)
40 #  include <sys/socket.h>
41 #endif
42
43 /* Is FD a socket or network connection? */
44 int
45 isnetconn (fd)
46      int fd;
47 {
48 #if defined (HAVE_GETPEERNAME) && !defined (SVR4_2) && !defined (__BEOS__)
49   int rv;
50   socklen_t l;
51   struct sockaddr sa;
52
53   l = sizeof(sa);
54   rv = getpeername(fd, &sa, &l);
55   /* Solaris 2.5 getpeername() returns EINVAL if the fd is not a socket. */
56   return ((rv < 0 && (errno == ENOTSOCK || errno == EINVAL)) ? 0 : 1);
57 #else /* !HAVE_GETPEERNAME || SVR4_2 || __BEOS__ */
58 #  if defined (SVR4) || defined (SVR4_2)
59   /* Sockets on SVR4 and SVR4.2 are character special (streams) devices. */
60   struct stat sb;
61
62   if (isatty (fd))
63     return (0);
64   if (fstat (fd, &sb) < 0)
65     return (0);
66 #    if defined (S_ISFIFO)
67   if (S_ISFIFO (sb.st_mode))
68     return (0);
69 #    endif /* S_ISFIFO */
70   return (S_ISCHR (sb.st_mode));
71 #  else /* !SVR4 && !SVR4_2 */
72 #    if defined (S_ISSOCK) && !defined (__BEOS__)
73   struct stat sb;
74
75   if (fstat (fd, &sb) < 0)
76     return (0);
77   return (S_ISSOCK (sb.st_mode));
78 #    else /* !S_ISSOCK || __BEOS__ */
79   return (0);
80 #    endif /* !S_ISSOCK || __BEOS__ */
81 #  endif /* !SVR4 && !SVR4_2 */
82 #endif /* !HAVE_GETPEERNAME || SVR4_2 || __BEOS__ */
83 }