在网络连接中,一般用heartbeat来检测设备是否在线。
但是如果有一台第三方的设备,没法在设备上制作heartbeat程序,那么可以用ping来检测该设备是否在线,相当于heartbeat了。
别忘了防火墙可能会屏蔽ping。我是粗暴的将防火墙关闭了。
以下是Linux中模拟ping命令的C代码:
/********************************************************
* IP报头格式数据结构定义在<netinet/ip.h>中 *
* ICMP数据结构定义在<netinet/ip_icmp.h>中 *
* 套接字地址数据结构定义在<netinet/in.h>中 *
********************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <signal.h>
#include <arpa/inet.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <unistd.h>
#include <netinet/in.h>
#include <netinet/ip.h>
#include <netinet/ip_icmp.h>
#include <netdb.h>
#include <setjmp.h>
#include <errno.h>
#define PACKET_SIZE 4096
#define MAX_WAIT_TIME 5
#define MAX_NO_PACKETS 10000
char *addr[];
char sendpacket[PACKET_SIZE];
char recvpacket[PACKET_SIZE];
int sockfd,datalen = 56;
int nsend = 0, nreceived = 0;
double temp_rtt[MAX_NO_PACKETS];
double all_time = 0;
double min = 0;
double max = 0;
double avg = 0;
double mdev = 0;
struct sockaddr_in dest_addr;
struct sockaddr_in from;
struct timeval tvrecv;
pid_t pid;
void statistics(int sig);
void send_packet(void);
void recv_packet(void);
void computer_rtt(void);
void tv_sub(struct timeval *out,struct timeval *in);
int pack(int pack_no);
int unpack(char *buf,int len);
unsigned short cal_checksum(unsigned short *addr,int len);
/*计算rtt最小、大值,平均值,算术平均数差*/
void computer_rtt()
{
double sum_avg = 0;
int i;
min = max = temp_rtt[0];
avg = all_time/nreceived;
for(i=0; i<nreceived; i++){
if(temp_rtt[i] < min)
min = temp_rtt[i];
else if(temp_rtt[i] > max)
max = temp_rtt[i];
if((temp_rtt[i]-avg) < 0)
sum_avg += avg - t