]> asedeno.scripts.mit.edu Git - 1ts-debian.git/blob - zephyr/lib/ZOpenPort.c
r4254@bucket (orig r244): kcr | 2008-01-20 14:40:42 -0500
[1ts-debian.git] / zephyr / lib / ZOpenPort.c
1 /* This file is part of the Project Athena Zephyr Notification System.
2  * It contains source for the ZOpenPort function.
3  *
4  *      Created by:     Robert French
5  *
6  *      $Id$
7  *
8  *      Copyright (c) 1987 by the Massachusetts Institute of Technology.
9  *      For copying and distribution information, see the file
10  *      "mit-copyright.h". 
11  */
12
13 #ifndef lint
14 static char rcsid_ZOpenPort_c[] = "$Id$";
15 #endif
16
17 #include <internal.h>
18 #include <sys/socket.h>
19
20 Code_t
21 ZOpenPort(u_short *port)
22 {
23     struct sockaddr_in bindin;
24     int len;
25     
26     (void) ZClosePort();
27
28     if ((__Zephyr_fd = socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
29         __Zephyr_fd = -1;
30         return (errno);
31     }
32
33     bindin.sin_family = AF_INET;
34
35     if (port && *port)
36         bindin.sin_port = *port;
37     else
38         bindin.sin_port = 0;
39
40     bindin.sin_addr.s_addr = INADDR_ANY;
41
42     if (bind(__Zephyr_fd, (struct sockaddr *)&bindin, sizeof(bindin)) < 0) {
43         if (errno == EADDRINUSE && port && *port)
44             return (ZERR_PORTINUSE);
45         else
46             return (errno);
47     }
48
49     if (!bindin.sin_port) {
50         len = sizeof(bindin);
51         if (getsockname(__Zephyr_fd, (struct sockaddr *)&bindin, &len))
52             return (errno);
53     }
54     
55     __Zephyr_port = bindin.sin_port;
56     __Zephyr_open = 1;
57
58     if (port)
59         *port = bindin.sin_port;
60
61     return (ZERR_NONE);
62 }