forked from shimonran/RDMA_Hello
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsockets.c
97 lines (82 loc) · 2.27 KB
/
sockets.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
/* vim: set noet: */
#include <stdio.h>
#include <unistd.h>
#include <netdb.h>
#include <sys/types.h>
#include <sys/socket.h>
#include "sockets.h"
int sock_connect(const char *servername, int port)
{
struct addrinfo *resolved_addr = NULL;
struct addrinfo *iterator;
char service[6];
int sockfd = -1;
int listenfd = 0;
int tmp;
struct addrinfo hints = {
.ai_flags = AI_PASSIVE,
.ai_family = AF_INET,
.ai_socktype = SOCK_STREAM
};
if (sprintf(service, "%d", port) < 0)
goto sock_connect_exit;
/* Resolve DNS address, use sockfd as temp storage */
sockfd = getaddrinfo(servername, service, &hints, &resolved_addr);
if (sockfd < 0) {
fprintf(stderr, "%s for %s:%d\n", gai_strerror(sockfd), servername, port); goto sock_connect_exit;
}
/* Search through results and find the one we want */
for (iterator = resolved_addr; iterator ; iterator = iterator->ai_next) {
sockfd = socket(iterator->ai_family, iterator->ai_socktype, iterator->ai_protocol);
if (sockfd >= 0) {
if (servername) {
/* Client mode. Initiate connection to remote */
if((tmp=connect(sockfd, iterator->ai_addr, iterator->ai_addrlen))) {
fprintf(stdout, "failed connect \n");
close(sockfd);
sockfd = -1;
}
}
else {
/* Server mode. Set up listening socket and accept a connection */
listenfd = sockfd;
sockfd = -1;
if(bind(listenfd, iterator->ai_addr, iterator->ai_addrlen))
goto sock_connect_exit;
listen(listenfd, 1);
sockfd = accept(listenfd, NULL, 0);
}
}
}
sock_connect_exit:
if(listenfd) close(listenfd);
if(resolved_addr) freeaddrinfo(resolved_addr);
if (sockfd < 0) {
if(servername)
fprintf(stderr, "Couldn't connect to %s:%d\n", servername, port);
else {
perror("server accept");
fprintf(stderr, "accept() failed\n");
}
}
return sockfd;
}
int sock_sync_data(int sock, int xfer_size, char *local_data, char *remote_data)
{
int rc;
int read_bytes = 0;
int total_read_bytes = 0;
rc = write(sock, local_data, xfer_size);
if(rc < xfer_size)
fprintf(stderr, "Failed writing data during sock_sync_data\n");
else
rc = 0;
while(!rc && total_read_bytes < xfer_size) {
read_bytes = read(sock, remote_data, xfer_size);
if(read_bytes > 0)
total_read_bytes += read_bytes;
else
rc = read_bytes;
}
return rc;
}