2 libfmail: Socket abstraction
4 Copyright (C) 2007 Carlos Daniel Ruvalcaba Valenzuela <clsdaniel@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 2 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 along
17 with this program; if not, write to the Free Software Foundation, Inc.,
18 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
25 #include <sys/types.h>
28 #include <netinet/in.h>
29 #include <arpa/inet.h>
30 #include <sys/socket.h>
32 #include <sys/ioctl.h>
34 #include <libfmail/socket.h>
36 /* TODO: Add more socket options like noblocking */
38 sock
= socket(AF_INET
, SOCK_STREAM
, 0);
39 self_addr
= (struct sockaddr_in
*)malloc(sizeof(struct sockaddr_in
));
42 Socket::Socket(int s
, struct sockaddr_in
*addr
){
47 /* TODO: Add hostname lookup for remote_addr */
48 int Socket::Connect(char *remote_addr
, int remote_port
){
52 if (!inet_aton(remote_addr
, &p
))
55 self_addr
->sin_family
= AF_INET
;
56 self_addr
->sin_port
= htons(remote_port
);
57 self_addr
->sin_addr
.s_addr
= p
.s_addr
;
59 slen
= sizeof(struct sockaddr_in
);
61 r
= connect(sock
, (struct sockaddr
*)(self_addr
), slen
);
65 int Socket::Bind(int port
){
68 self_addr
->sin_family
= AF_INET
;
69 self_addr
->sin_port
= htons(port
);
70 self_addr
->sin_addr
.s_addr
= htonl(INADDR_ANY
);
72 slen
= sizeof(struct sockaddr_in
);
74 return bind(sock
, (struct sockaddr
*)self_addr
, slen
);
77 int Socket::Listen(int queue
){
79 r
= listen(sock
, queue
);
83 int Socket::Write(const char *buffer
, int len
){
84 return write(sock
, buffer
, len
);
87 int Socket::Read(char *buffer
, int len
){
88 return read(sock
, buffer
, len
);
91 Socket
*Socket::Accept(){
93 struct sockaddr_in
*client
;
97 client
= (struct sockaddr_in
*)malloc(sizeof(struct sockaddr_in
));
98 clen
= sizeof(struct sockaddr_in
);
100 client_socket
= accept(sock
, (struct sockaddr
*)client
, &clen
);
101 s
= new Socket(client_socket
, client
);