Implemented initial core/ping.

A fake plaintext ping/pong implementation, for now it's just
   to use as a POC for multistream and secio.
This commit is contained in:
Jose Marcial Vieira Bisneto 2017-02-09 23:53:58 -03:00
parent de6c4b2495
commit 0522bedd2a
6 changed files with 93 additions and 2 deletions

View file

@ -2,7 +2,7 @@ CC = gcc
CFLAGS = -O0 -I../include -I../../c-libp2p/include -I../../c-protobuf -Wall
LFLAGS =
DEPS = builder.h ipfs_node.h
OBJS = builder.o daemon.o null.o
OBJS = builder.o daemon.o null.o ping.o
%.o: %.c $(DEPS)
$(CC) -c -o $@ $< $(CFLAGS)

View file

@ -1,20 +1,39 @@
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>
#include <unistd.h>
#include <pthread.h>
#include "libp2p/net/p2pnet.h"
#include "ipfs/core/daemon.h"
#define BUF_SIZE 4096
void *ipfs_null_connection (void *ptr)
{
struct null_connection_params *connection_param;
char b[BUF_SIZE];
int len;
connection_param = (struct null_connection_params*) ptr;
// TODO: multistream + secio + message.
fprintf(stderr, "Connection %d, count %d\n", connection_param->socket, *(connection_param->count));
for(;;) {
len = socket_read(connection_param->socket, b, sizeof(b)-1, 0);
if (len > 0) {
while (b[len-1] == '\r' || b[len-1] == '\n') len--;
b[len] = '\0';
fprintf(stderr, "Recv: '%s'\n", b);
if (strcmp (b, "ping") == 0) {
socket_write(connection_param->socket, "pong", 4, 0);
}
} else if(len < 0) {
break;
}
}
close (connection_param->socket); // close socket.
(*(connection_param->count))--; // update counter.
free (connection_param);

63
core/ping.c Normal file
View file

@ -0,0 +1,63 @@
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/time.h>
#include <arpa/inet.h>
#include "libp2p/net/p2pnet.h"
#define BUF_SIZE 4096
int ipfs_ping (int argc, char **argv)
{
int socketfd, i, count=10, tcount = 0;
uint32_t ipv4;
uint16_t port;
char b[BUF_SIZE];
size_t len;
struct timeval time;
long cur_time, old_time;
double ms, total = 0;
if (inet_pton (AF_INET, argv[2], &ipv4) == 0) {
fprintf(stderr, "Unable to use '%s' as an IP address.\n", argv[1]);
return 1;
}
if ((port = atoi(argv[3])) == 0) {
fprintf(stderr, "Unable to use '%s' port.\n", argv[2]);
return 1;
}
if ((socketfd = socket_tcp4()) <= 0) {
perror("can't create socket");
return 1;
}
if (socket_connect4(socketfd, ipv4, port) < 0) {
perror("fail to connect");
return 1;
}
fprintf(stderr, "PING %s.\n", argv[2]);
for (i=0 ; i < count ; i++) {
if (gettimeofday (&time, 0)) return -1;
old_time = 1000000 * time.tv_sec + time.tv_usec;
socket_write(socketfd, "ping", 4, 0);
len = socket_read(socketfd, b, sizeof(b), 0);
if (len == 4 && memcmp(b, "pong", 4) == 0) {
if (gettimeofday (&time, 0)) return -1;
cur_time = 1000000 * time.tv_sec + time.tv_usec;
ms = (cur_time - old_time) / 1000.0;
total += ms; tcount++;
fprintf(stderr, "Pong received: time=%.2f ms\n", ms);
}
sleep (1);
}
fprintf(stderr, "Average latency: %.2fms\n", total / tcount);
return 0;
}