3 * Copyright (C) 2008 Tomas 'ZeXx86' Jedrzejek (zexx86@gmail.com)
4 * Copyright (C) 2009 Tomas 'ZeXx86' Jedrzejek (zexx86@gmail.com)
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/>.
32 #include <sys/socket.h>
35 #include <netinet/in.h>
36 #include <arpa/inet.h>
37 #include <sys/types.h>
42 int net_send (char *data
, unsigned len
)
49 if ((ret
= send (net
.sock
, data
, len
, 0)) == -1) {
50 printf ("ERROR -> send (%d) = -1\n", net
.sock
);
57 int net_connect (char *server
, int port
)
61 /* connect to im server */
63 // Check info about remote host
64 if ((host
= gethostbyname ((char *) server
)) == NULL
) {
65 printf ("Wrong address -> %s:%d\n", server
, port
);
69 if ((net
.sock
= socket (AF_INET
, SOCK_STREAM
, IPPROTO_TCP
)) == -1) {
70 printf ("Cant create socket\n");
74 // Fill structure sockaddr_in
76 net
.conn
.sin_family
= AF_INET
;
77 // 2) Port of remote server
78 net
.conn
.sin_port
= htons (port
);
79 // 3) Remote ip address
80 memcpy (&(net
.conn
.sin_addr
), host
->h_addr
, host
->h_length
);
83 if (connect (net
.sock
, (struct sockaddr
*) &net
.conn
, sizeof (net
.conn
)) == -1) {
84 printf ("Connection cant be estabilished -> %s:%d\n", server
, port
);
88 net
.buffer
= (char *) malloc (sizeof (char) * NET_BUFFER_SIZE
);
100 int net_switchmode ()
102 /* set socket "sock" to non-blocking */
103 int oldFlag
= fcntl (net
.sock
, F_GETFL
, 0);
104 if (fcntl (net
.sock
, F_SETFL
, oldFlag
| O_NONBLOCK
) == -1) {
105 printf ("Cant set socket to nonblocking mode\n");
112 static int strnchrn (char *str
, unsigned len
)
117 if (str
[l
] == '\n') {
131 int ret
= recv (net
.sock
, net
.buffer
, NET_BUFFER_SIZE
-1, 0);
136 net
.buffer
[ret
] = '\0';
139 int l
= strnchrn (net
.buffer
+len
, ret
-len
);
144 proto_handler (net
.buffer
+len
, l
);
157 printf ("ERROR -> Disconnected by server\n");
172 /** INIT NETWORK function */
175 return net_connect (cfg
->server
, cfg
->port
);;