3 * Copyright (C) 2009 Tomas 'ZeXx86' Jedrzejek (zexx86@zexos.org)
5 * This program is free software: you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation, either version 3 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License
16 * along with this program. If not, see <http://www.gnu.org/licenses/>.
26 #include <arpa/inet.h>
27 #include <netinet/in.h>
28 #include <sys/socket.h>
33 static struct sockaddr_in serverSock
; // Remote socket
34 static struct hostent
*host
; // Remote host
38 /* set socket "sock" to non-blocking */
39 int oldFlag
= fcntl (sock
, F_GETFL
, 0);
40 if (fcntl (sock
, F_SETFL
, oldFlag
| O_NONBLOCK
) == -1) {
41 printf ("Cant set socket to nonblocking mode\n");
48 int net_send (char *buf
, unsigned len
)
50 return send (sock
, buf
, len
, 0);
53 int net_recv (char *buf
, unsigned len
)
55 return recv (sock
, buf
, len
, 0);
58 int net_connect (char *server
, int port
)
60 // Let's get info about remote computer
61 if ((host
= gethostbyname ((char *) server
)) == NULL
) {
62 printf ("Wrong address -> %s:%d\n", server
, port
);
67 if ((sock
= socket (AF_INET
, SOCK_STREAM
, IPPROTO_TCP
)) == -1) {
68 printf ("Cant create socket\n");
72 // Fill structure sockaddr_in
73 // 1) Family of protocols
74 serverSock
.sin_family
= AF_INET
;
75 // 2) Number of server port
76 serverSock
.sin_port
= htons (port
);
77 // 3) Setup ip address of server, where we want to connect
78 memcpy (&(serverSock
.sin_addr
), host
->h_addr
, host
->h_length
);
80 // Now we are able to connect to remote server
81 if (connect (sock
, (struct sockaddr
*) &serverSock
, sizeof (serverSock
)) == -1) {
82 printf ("Connection cant be estabilished -> %s:%d\n", server
, port
);
86 printf ("zjab -> connected to %s:%d server\n", server
, port
);