3 * Copyright (C) 2008 Tomas 'ZeXx86' Jedrzejek (zexx86@zexos.org)
4 * Copyright (C) 2009 Tomas 'ZeXx86' Jedrzejek (zexx86@zexos.org)
6 * This program is free software: you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation, either version 3 of the License, or
9 * (at your option) any later version.
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
16 * You should have received a copy of the GNU General Public License
17 * along with this program. If not, see <http://www.gnu.org/licenses/>.
25 #include <sys/socket.h>
26 #include <netinet/in.h>
27 #include <arpa/inet.h>
35 static struct sockaddr_in serverSock
;
36 static struct sockaddr_in6 serverSock6
;
37 static struct hostent
*host
;
41 /** Network Send function */
42 int net_send (char *buf
, unsigned len
)
44 int ret
= send (fd
, buf
, len
, 0);
51 unsigned strlenn (char *str
, unsigned len
)
55 while (str
[i
] != '\n') {
69 int ret
= recv (fd
, buf
, BUFSIZE
-1, 0);
74 //printf ("net_loop () -> recv (): '%s' : %d\n", buf, ret);
76 if (!proto_handler (buf
, ret
)) {
77 printf ("ERROR -> proto_handler () failed\n");
86 printf ("INFO -> Connection closed by server\n");
100 printf ("net_close () -> close (%d)\n", fd
);
105 int init_net (char *address
, int port
, int flags
)
109 if (flags
& NET_IPV6
)
112 if ((host
= gethostbyname ((char *) address
)) == NULL
) {
113 printf ("Wrong address -> %s:%d\n", address
, port
);
117 if ((fd
= socket (proto
, SOCK_STREAM
, IPPROTO_TCP
)) == -1) {
118 printf ("Cant create socket\n");
122 if (flags
& NET_IPV6
) {
123 serverSock6
.sin6_family
= proto
;
124 serverSock6
.sin6_port
= htons (port
);
125 memcpy (&(serverSock6
.sin6_addr
), host
->h_addr
, host
->h_length
);
127 if (connect (fd
, (struct sockaddr
*) &serverSock6
, sizeof (serverSock6
)) == -1) {
128 printf ("Connection cant be estabilished -> %s:%d\n", address
, port
);
132 serverSock
.sin_family
= proto
;
133 serverSock
.sin_port
= htons (port
);
134 memcpy (&(serverSock
.sin_addr
), host
->h_addr
, host
->h_length
);
136 if (connect (fd
, (struct sockaddr
*) &serverSock
, sizeof (serverSock
)) == -1) {
137 printf ("Connection cant be estabilished -> %s:%d\n", address
, port
);
142 int oldFlag
= fcntl (fd
, F_GETFL
, 0);
143 if (fcntl (fd
, F_SETFL
, oldFlag
| O_NONBLOCK
) == -1) {
144 printf ("Cant set socket to nonblocking mode\n");
148 buf
= (char *) malloc (sizeof (char) * BUFSIZE
);
151 printf ("Receive buffer -> out of memory !\n");