Added a directory for tools and a todo-list script
[fmail.git] / src / socket.cpp
blob20c3e74a956466980b884d72562d69826f06514f
1 /*
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.
21 #include <stdio.h>
22 #include <stdlib.h>
23 #include <string.h>
24 #include <malloc.h>
25 #include <sys/types.h>
26 #include <sys/uio.h>
27 #include <unistd.h>
28 #include <netinet/in.h>
29 #include <arpa/inet.h>
30 #include <sys/socket.h>
31 #include <sys/time.h>
32 #include <sys/ioctl.h>
34 #include <libfmail/socket.h>
36 /* TODO: Add more socket options like noblocking */
37 Socket::Socket(){
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){
43 sock = s;
44 self_addr = addr;
47 /* TODO: Add hostname lookup for remote_addr */
48 int Socket::Connect(char *remote_addr, int remote_port){
49 int slen, r;
50 struct in_addr p;
52 if (!inet_aton(remote_addr, &p))
53 return 0;
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);
62 return r;
65 int Socket::Bind(int port){
66 int slen;
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){
78 int r;
79 r = listen(sock, queue);
80 return r;
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(){
92 int client_socket;
93 struct sockaddr_in *client;
94 socklen_t clen;
95 Socket *s;
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);
103 return s;
106 int Socket::Close(){
107 return close(sock);