linux下判斷網絡是否連接
本文改寫自網上的一個程序,原始程序中為阻塞式調用,而且有現成創建的過程,非常不利于集成到自己程序中,因此對原始程序進行改造,使其可以完成發送一個imcp包的方式來判斷網絡連通,只需要調用改進后的
bool NetIsOK()
函數即可,該函數返回true即表示網絡狀態良好,否則表示網絡狀態不連同,本程序中只發送了一個icmp包,在實際應用中可以根據需要改進為發送多個imcp包。修改之后的程序為:只需要調用函數NetIsOK()即可。源碼如下所示:
#include <stdio.h>
#include <signal.h>
#include <stdlib.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/wait.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 <errno.h>
#define MAX_WAIT_TIME 1
#define MAX_NO_PACKETS 1
#define ICMP_HEADSIZE 8
#define PACKET_SIZE 4096
struct timeval tvsend,tvrecv;
struct sockaddr_in dest_addr,recv_addr;
int sockfd;
pid_t pid;
char sendpacket[PACKET_SIZE];
char recvpacket[PACKET_SIZE];
//函數定義
void timeout(int signo);
unsigned short cal_chksum(unsigned short *addr,int len);
int pack(int pkt_no,char *sendpacket);
int send_packet(int pkt_no,char *sendpacket);
int recv_packet(int pkt_no,char *recvpacket);
int unpack(int cur_seq,char *buf,int len);
void tv_sub(struct timeval *out,struct timeval *in);
void _CloseSocket();
bool NetIsOk()
{
double rtt;
struct hostent *host;
struct protoent *protocol;
int i,recv_status;
#ifdef _USE_DNS //如果定義該宏,則可以使用域名進行判斷網絡連接,例如www.baidu.com
/* 設置目的地址信息 */
char hostname[32];
sprintf(hostname,"%s","www.baidu.com")
bzero(&dest_addr, sizeof(dest_addr));
dest_addr.sin_family = AF_INET;
if((host=gethostbyname(hostname))==NULL)
{
printf("[NetStatus] error : Can't get serverhost info!\n"