#include "benchmarks.h"
#include <libssh/libssh.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <errno.h>
#include <sys/time.h>
#define PING_PROGRAM "/bin/ping"
int benchmarks_ping_latency (const char *host, float *average){
const char *ptr;
char cmd[256];
char line[1024];
FILE *fd;
int found=0;
ptr=strchr(host,'@');
if(ptr)
ptr++;
else
ptr=host;
snprintf(cmd,sizeof(cmd),"%s -n -q -c3 %s",PING_PROGRAM, ptr);
fd=popen(cmd,"r");
if(fd==NULL){
fprintf(stderr,"Error executing command : %s\n", strerror(errno));
return -1;
}
while(!found && fgets(line,sizeof(line),fd)!=NULL){
if(strstr(line,"rtt")){
ptr=strchr(line,'=');
if(ptr==NULL)
goto parseerror;
ptr=strchr(ptr,'/');
if(ptr==NULL)
goto parseerror;
*average=strtof(ptr+1,NULL);
found=1;
break;
}
}
if(!found)
goto parseerror;
pclose(fd);
return 0;
parseerror:
fprintf(stderr,"Parse error : couldn't locate average in %s",line);
pclose(fd);
return -1;
}
void timestamp_init(struct timestamp_struct *ts){
gettimeofday(&ts->timestamp,NULL);
}
float elapsed_time(struct timestamp_struct *ts){
struct timeval now;
time_t secdiff;
long usecdiff;
gettimeofday(&now,NULL);
secdiff=now.tv_sec - ts->timestamp.tv_sec;
usecdiff=now.tv_usec - ts->timestamp.tv_usec;
return (float) (secdiff*1000) + ((float)usecdiff)/1000;
}
int benchmarks_ssh_latency(ssh_session session, float *average){
float times[3];
struct timestamp_struct ts;
int i;
ssh_channel channel;
channel=ssh_channel_new(session);
if(channel==NULL)
goto error;
if(ssh_channel_open_session(channel)==SSH_ERROR)
goto error;
for(i=0;i<3;++i){
timestamp_init(&ts);
if(ssh_channel_request_env(channel,"TEST","test")==SSH_ERROR &&
ssh_get_error_code(session)==SSH_FATAL)
goto error;
times[i]=elapsed_time(&ts);
}
ssh_channel_close(channel);
ssh_channel_free(channel);
channel=NULL;
printf("SSH request times : %f ms ; %f ms ; %f ms\n", times[0], times[1], times[2]);
*average=(times[0]+times[1]+times[2])/3;
return 0;
error:
fprintf(stderr,"Error calculating SSH latency : %s\n",ssh_get_error(session));
if(channel)
ssh_channel_free(channel);
return -1;
}