-
Notifications
You must be signed in to change notification settings - Fork 4
/
mpsock_tcp.c
104 lines (81 loc) · 2.02 KB
/
mpsock_tcp.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
/**
* Multipath Multi-source HTTP (mHTTP)
*
* Developers: Juhoon Kim ([email protected]), Karl Fischer
*
*/
#include "mpsock_tcp.h"
int tcpconnect(tcpsock *sock)
{
struct sockaddr_in pin;
memset(&pin, 0, sizeof(pin));
pin.sin_family = PF_INET;
pin.sin_addr.s_addr = sock->ip;
pin.sin_port = htons(80);
return f_connect(sock->fd, (struct sockaddr *) &pin, sizeof(struct sockaddr_in));
}
void tcpclose(tcpsock *sock)
{
close(sock->fd);
}
void freesock(tcpsock *sock)
{
free(sock);
}
tcpsock *newtcp(const char *host, unsigned long ip, unsigned short port)
{
tcpsock *s = malloc(sizeof(tcpsock));
memset(s, 0, sizeof(tcpsock));
s->fd = f_socket(AF_INET, SOCK_STREAM, 0);
s->ip = ip;
s->port = port;
strncpy(s->host, host, sizeof(host));
return s;
}
int tcpsend(tcpsock *sock, void *data, size_t len)
{
size_t sent = 0;
size_t cnt;
uint8_t *seek;
while (sent < len) {
seek = (uint8_t *) data + sent;
cnt = f_write(sock->fd, seek, sizeof(uint8_t) * (len - sent));
sent += cnt;
if (cnt < 0)
return cnt;
}
return sent;
}
//For receiving information which you already know the size of.
int tcprecv(tcpsock *sock, void *buffer, size_t len)
{
int recvd;
size_t total = 0;
while (total < len) {
recvd = read(sock->fd, (uint8_t *) buffer + total, len - total);
if (recvd == -1)
return -1;
else
total += recvd;
}
return total;
}
//Takes whatever information is waiting on your socket (up to 'sz' bytes)
//and puts it into the memory pointed to by 'buffer'. As the code shows,
//it works just like the 'recv(//)' system call
int tcprecv_next(tcpsock *sock, void *buffer, size_t len)
{
return f_read(sock->fd, (uint8_t *) buffer, len);
}
tcpsock * tcpaccept(tcpsock *listener)
{
socklen_t len;
struct sockaddr_storage sockaddr_str;
len = sizeof(struct sockaddr_storage);
tcpsock *s = malloc(sizeof(tcpsock));
int accepted = accept(listener->fd, (struct sockaddr *)&sockaddr_str, &len);
if (accepted == -1)
return NULL;
s->fd = accepted;
return s;
}