/[cvs]/eggdrop1.9/testcode/my_socket.c
ViewVC logotype

Contents of /eggdrop1.9/testcode/my_socket.c

Parent Directory Parent Directory | Revision Log Revision Log | View Revision Graph Revision Graph


Revision 1.1 - (show annotations) (download) (as text)
Tue Jan 8 00:09:09 2002 UTC (18 years, 2 months ago) by stdarg
Branch: MAIN
File MIME type: text/x-chdr
Err, I don't know if I already added these files or not, so I'll add them again.

1 #include <stdio.h>
2 #include <stdlib.h>
3 #include <sys/socket.h>
4 #include <netinet/in.h>
5 #include <arpa/inet.h>
6 #include <fcntl.h>
7 #include <errno.h>
8
9 #include "my_socket.h"
10
11 //#define DO_IPV6
12 #define DO_IPV4
13
14 /* Return values: */
15 /* -1: invalid ip address */
16 /* -2: socket() failure */
17 /* -3: bind() failure */
18 /* -4: connect() failure */
19 int socket_create(char *ipaddr, int port, int flags)
20 {
21 int sock, pfamily, err, len;
22 struct sockaddr *name;
23 #ifdef DO_IPV4
24 struct sockaddr_in ipv4_name;
25 #endif
26 #ifdef DO_IPV6
27 struct sockaddr_in6 ipv6_name;
28 #endif
29
30 if (!ipaddr) {
31 #ifdef DO_IPV6
32 ipaddr = "0:0:0:0:0:0:0:0";
33 #else
34 ipaddr = "0.0.0.0";
35 #endif
36 }
37
38 /* Resolve the ip address. */
39 #ifdef DO_IPV6
40 err = inet_pton(AF_INET6, ipaddr, &ipv6_name.sin6_addr);
41 if (err <= 0) {
42 #ifndef DO_IPV4
43 return(err);
44 #else
45 err = inet_pton(AF_INET, ipaddr, &ipv4_name.sin_addr);
46 if (err <= 0) return(-1);
47 pfamily = PF_INET;
48 name = (struct sockaddr *)&ipv4_name;
49 len = sizeof(ipv4_name);
50 ipv4_name.sin_port = htons(port);
51 ipv4_name.sin_family = AF_INET;
52 #endif
53 }
54 else {
55 pfamily = PF_INET6;
56 name = (struct sockaddr *)&ipv6_name;
57 len = sizeof(ipv6_name);
58 ipv6_name.sin6_port = htons(port);
59 ipv6_name.sin6_family = AF_INET6;
60 }
61 #else
62 err = inet_aton(ipaddr, &ipv4_name.sin_addr);
63 if (err <= 0) return(-1);
64 pfamily = PF_INET;
65 name = (struct sockaddr *)&ipv4_name;
66 len = sizeof(ipv4_name);
67 ipv4_name.sin_port = htons(port);
68 ipv4_name.sin_family = AF_INET;
69 #endif
70
71 /* Create the socket! */
72 if (flags & SOCKET_UDP) sock = socket(pfamily, SOCK_DGRAM, 0);
73 else sock = socket(pfamily, SOCK_STREAM, 0);
74 if (sock < 0) return(-2);
75
76 if (flags & SOCKET_NONBLOCK) socket_set_nonblock(sock, 1);
77
78 if (flags & SOCKET_SERVER) {
79 int yes = 1;
80 setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(int));
81 err = bind(sock, name, len);
82 if (err < 0) return(-3);
83 listen(sock, 50);
84 }
85 else {
86 err = connect(sock, name, len);
87 if (err < 0 && errno != EINPROGRESS) return(-4);
88 }
89
90 /* Yay, we're done. */
91 return(sock);
92 }
93
94 int socket_set_nonblock(int sock, int value)
95 {
96 int oldflags = fcntl(sock, F_GETFL, 0);
97 if (oldflags == -1) return -1;
98 if (value != 0) oldflags |= O_NONBLOCK;
99 else oldflags &= ~O_NONBLOCK;
100
101 return fcntl(sock, F_SETFL, oldflags);
102 }

webmaster@eggheads.org
ViewVC Help
Powered by ViewVC 1.1.23