source: trunk/MagicSoft/Control/SubsystemIO/socket_functions.c@ 5059

Last change on this file since 5059 was 1041, checked in by casaldaliga, 23 years ago
First release
File size: 2.1 KB
Line 
1#include "socket_functions.h"
2#include <stdio.h>
3#include <stdlib.h>
4#include <sys/socket.h>
5#include <netinet/in.h>
6#include <netdb.h>
7
8 int
9 make_socket (unsigned short int port)
10 {
11 int sock;
12 struct sockaddr_in name;
13
14 /* Create the socket. */
15 sock = socket (PF_INET, SOCK_STREAM, 0);
16 if (sock < 0)
17 {
18 perror ("socket");
19 exit (EXIT_FAILURE);
20 }
21
22 /* Give the socket a name. */
23 name.sin_family = AF_INET;
24 name.sin_port = htons (port);
25 name.sin_addr.s_addr = htonl (INADDR_ANY);
26 /*
27 * Set up to reuse server addresses automatically and bind to the
28 * specified port.
29 * Look in CreateSocket in tclUnixChan.c from tcl source
30 * If this is not present when server closes before client, the next
31 * time server starts -> bind: Address in use
32 */
33
34 int status = 1;
35 (void) setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (char *) &status,
36 sizeof(status));
37 if (status == -1) {
38 perror ("reuse");
39 }
40
41 if (bind (sock, (struct sockaddr *) &name, sizeof (name)) < 0)
42 {
43 perror ("bind");
44 exit (EXIT_FAILURE);
45 }
46
47 return sock;
48 }
49
50 void
51 init_sockaddr (struct sockaddr_in *name,
52 const char *hostname,
53 unsigned short int port)
54 {
55 struct hostent *hostinfo;
56
57 name->sin_family = AF_INET;
58 name->sin_port = htons (port);
59 hostinfo = gethostbyname (hostname);
60 if (hostinfo == NULL)
61 {
62 fprintf (stderr, "Unknown host %s.\n", hostname);
63 exit (EXIT_FAILURE);
64 }
65 name->sin_addr = *(struct in_addr *) hostinfo->h_addr;
66 }
67
68int prepare_socket( int sock )
69{
70 /*
71 * Set up to reuse server addresses automatically and bind to the
72 * specified port.
73 * Look in CreateSocket in tclUnixChan.c from tcl source
74 * If this is not present when server closes before client, the next
75 * time server starts -> bind: Address in use
76 */
77
78 int status = 1;
79 (void) setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (char *) &status,
80 sizeof(status));
81 if (status == -1) {
82 perror ("reuse");
83 }
84 return status;
85}
Note: See TracBrowser for help on using the repository browser.