一个不用root权限的ping功能代码

测试可以在 mac 和 linux 下运行,不用 root 权限

执行 Ping_Check_NetWork 即可

#include <stdio.h>

#include <stdlib.h>

#include <sys/socket.h>

#include <netinet/in.h>

#include <stdint.h>

#include <netdb.h>

#include <arpa/inet.h>

#include <unistd.h>

#include <string.h>

#include <sys/time.h>

#include <errno.h>

#include <sys/stat.h>

#include <pthread.h>

#include "../log/log.h"

#define DATA_SIZE 32

#define MAX_RECV_SIZE 1024

typedef struct _TAG_IP_HEADER

{

    u_int8_t    ip_head_verlen;

    u_int8_t    ip_tos;

    u_int16_t  ip_length;

    u_int16_t  ip_id;

    u_int16_t  ip_flags;

    u_int8_t    ip_ttl;

    u_int8_t    ip_protacol;

    u_int16_t  ip_checksum;

    u_int32_t  ip_source;

    u_int32_t  ip_destination;

} IP_HEADER;

typedef struct _TAG_IMCP_HEADER

{

    u_int8_t    icmp_type;

    u_int8_t    icmp_code;

    u_int16_t  check_sum;

    u_int16_t  icmp_id;

    u_int16_t  icmp_seq;

} ICMP_HEADER;

typedef struct _TAG_ICMP_PACKET

{

    ICMP_HEADER    icmp_header;

    struct timeval  icmp_time;

    u_int16_t      icmp_sum_flag;

    u_int8_t        imcp_data[DATA_SIZE];

} ICMP_PACKET;

typedef struct _TAG_THREAD_DATA

{

    int        fd;

    u_int32_t  times;

    ICMP_PACKET * icmp_packet;

    char        * buffer;

    u_int32_t  buffer_len;

    struct sockaddr_in * sockaddr;

    u_int8_t    send_flag;

} THREAD_DATA;

static u_int16_t generation_checksum(u_int16_t * buf, u_int32_t size);

static double get_time_interval(struct timeval * start, struct timeval * end);

u_int16_t generation_checksum(u_int16_t * buf, u_int32_t size)

{

    u_int64_t cksum = 0;

    while(size > 1)

    {

        cksum += *buf++;

        size -= sizeof(u_int16_t);

    }

    if(size)

    {

        cksum += *buf++;

    }

    cksum =  (cksum>>16) + (cksum & 0xffff);

    cksum += (cksum>>16);

    return (u_int16_t)(~cksum);

}

static double get_time_interval(struct timeval * start, struct timeval * end)

{

    double interval;

    struct timeval tp;

    tp.tv_sec = end->tv_sec - start->tv_sec;

    tp.tv_usec = end->tv_usec - start->tv_usec;

    if(tp.tv_usec < 0)

    {

        tp.tv_sec -= 1;

        tp.tv_usec += 1000000;

    }

    interval = tp.tv_sec * 1000 + tp.tv_usec * 0.001;

    return interval;

}

static void * send_imcp(void *arg)

{

    u_int8_t *flag  = NULL;

    int times      = -1;

    int fd          = -1;

    struct sockaddr_in * dest_socket_addr;

    ICMP_HEADER *icmp_header = NULL;

    ICMP_PACKET *icmp_packet = NULL;

    THREAD_DATA *thread_data = (THREAD_DATA *)arg;

    if (thread_data == NULL)

    {

        return NULL;

    }

    dest_socket_addr = thread_data->sockaddr;

    if (dest_socket_addr == NULL)

    {

        return NULL;

    }

    flag  = &thread_data->send_flag;

    if (flag == NULL)

    {

        return NULL;

    }

    times = thread_data->times;

    fd = thread_data->fd;

    if (fd <= 0)

    {

        return NULL;

    }

    icmp_packet = thread_data->icmp_packet;

    if (icmp_packet == NULL)

    {

        return NULL;

    }

    icmp_header = &(icmp_packet->icmp_header);

    if (icmp_header == NULL)

    {

        return NULL;

    }

    for (int i = 0; i < thread_data->times; i++)

    {

        long result = -1;

        icmp_header->icmp_seq = htons(i);

        icmp_header->check_sum = 0;

        gettimeofday(&icmp_packet->icmp_time, NULL);

        icmp_packet->icmp_sum_flag = 0;

        icmp_header->check_sum = generation_checksum((u_int16_t *) icmp_packet, sizeof(ICMP_PACKET));

        result = sendto(fd, icmp_packet, sizeof(ICMP_PACKET), 0, (struct sockaddr *)dest_socket_addr,

                        sizeof(struct sockaddr_in));

        if (result == -1)

        {

            ERROR_LOG(DOWNLOAD_LOG, "PING: sendto: Network is unreachable\n");

            continue;

        }

        sleep(1);

    }

    *flag = 0;

    return NULL;

}

static void * recv_imcp(void *arg)

{

    u_int8_t *flag  = NULL;

    int times      = -1;

    int fd          = -1;

    ICMP_HEADER *icmp_header = NULL;

    ICMP_PACKET *icmp_packet = NULL;

    THREAD_DATA *thread_data = (THREAD_DATA *)arg;

    if (thread_data == NULL)

    {

        return NULL;

    }

    flag  = &thread_data->send_flag;

    if (flag == NULL)

    {

        return NULL;

    }

    times = thread_data->times;

    fd = thread_data->fd;

    if (fd <= 0)

    {

        return NULL;

    }

    icmp_packet = thread_data->icmp_packet;

    if (icmp_packet == NULL)

    {

        return NULL;

    }

    icmp_header = &(icmp_packet->icmp_header);

    if (icmp_header == NULL)

    {

        return NULL;

    }

    struct sockaddr_in from;

    socklen_t from_packet_len;

    long read_length;

    char recv_buf[MAX_RECV_SIZE];

    struct timeval end;

    from_packet_len = sizeof(struct sockaddr_in);

    for (int index = 0; index < times && *flag == 1;)

    {

        read_length = recvfrom(fd, recv_buf, MAX_RECV_SIZE, 0,

                              (struct sockaddr*)&from, &from_packet_len);

        gettimeofday( &end, NULL );

        if(read_length != -1)

        {

            IP_HEADER * recv_ip_header = (IP_HEADER*)recv_buf;

            int ip_ttl = (int)recv_ip_header->ip_ttl;

            ICMP_PACKET * recv_icmp = (ICMP_PACKET *)(recv_buf +

                                                      (recv_ip_header->ip_head_verlen & 0x0F) * 4);

            if(recv_icmp->icmp_header.icmp_type != 0)

            {

                ERROR_LOG(DOWNLOAD_LOG, "PING:error type %d received, error code %d \n", recv_icmp->icmp_header.icmp_type, recv_icmp->icmp_header.icmp_code);

                continue;

            }

            if (recv_icmp->icmp_sum_flag != icmp_packet->icmp_sum_flag)

            {

                ERROR_LOG(DOWNLOAD_LOG, "PING: check sum fail.\n");

                continue;

            }

            if(read_length >= (0 + sizeof(ICMP_PACKET)))

            {

                index++;

                snprintf(thread_data->buffer, thread_data->buffer_len, "%s%ld bytes from (%s): icmp_seq=%d time=%.2f ms\n",

                thread_data->buffer, read_length, inet_ntoa(from.sin_addr),

                recv_icmp->icmp_header.icmp_seq / 256, get_time_interval(&recv_icmp->icmp_time, &end));



                INFO_LOG(DOWNLOAD_LOG, "%ld bytes from (%s): icmp_seq=%d ttl=%d time=%.2f ms\n",

                        read_length, inet_ntoa(from.sin_addr), recv_icmp->icmp_header.icmp_seq / 256,

                        ip_ttl, get_time_interval(&recv_icmp->icmp_time, &end));

            }

        }

        else

        {

            if (errno != EAGAIN)

            {

                ERROR_LOG(DOWNLOAD_LOG, "PING: receive data error: %s\n", strerror(errno));

                snprintf(thread_data->buffer, thread_data->buffer_len, "receive data error: %s\n", strerror(errno));

            }

        }

    }

    return NULL;

}

int Ping_Check_NetWork(const char * domain, u_int32_t times, char * res_buffer, int buffer_len)

{

    int ret = -1;

    int client_fd = -1;

    int size = 50 * MAX_RECV_SIZE;

    struct timeval timeout;

    ICMP_PACKET * icmp_packet = NULL;

    ICMP_HEADER * icmp_header = NULL;

    char * hostName = NULL;

    in_addr_t dest_ip;

    struct sockaddr_in dest_socket_addr;

    pthread_t send_pid;

    pthread_t recv_pid;

    THREAD_DATA thread_data;

    if (res_buffer == NULL || domain == NULL || buffer_len == 0)

    {

        ERROR_LOG(DOWNLOAD_LOG, "res_buffer: %s, domain: %s, buffer_len: %d\n", res_buffer, domain, buffer_len);

        return ret;

    }

    dest_ip = inet_addr(domain);

    if (dest_ip == INADDR_NONE)

    {

        struct hostent* p_hostent = gethostbyname(domain);

        if(p_hostent)

        {

            dest_ip = (*(in_addr_t*)p_hostent->h_addr);

            hostName = p_hostent->h_name;

        }

    }

    if (dest_ip == INADDR_NONE)

    {

        return ret;

    }

    client_fd = socket(AF_INET, SOCK_DGRAM, IPPROTO_ICMP);

    if (client_fd == -1)

    {

        ERROR_LOG(DOWNLOAD_LOG, "socket error: %s!\n", strerror(errno));

        return ret;

    }

    timeout.tv_sec = 3;

    timeout.tv_usec = 0;

    setsockopt(client_fd, SOL_SOCKET, SO_RCVBUF, &size, sizeof(size));

    if(setsockopt(client_fd, SOL_SOCKET, SO_RCVTIMEO, &timeout, sizeof(struct timeval)))

    {

        ERROR_LOG(DOWNLOAD_LOG, "setsocketopt SO_RCVTIMEO error: %s\n", strerror(errno));

        return ret;

    }

    if(setsockopt(client_fd, SOL_SOCKET, SO_SNDTIMEO, &timeout, sizeof(struct timeval)))

    {

        ERROR_LOG(DOWNLOAD_LOG, "setsockopt SO_SNDTIMEO error: %s\n", strerror(errno));

        return ret;

    }

    memset(dest_socket_addr.sin_zero, 0, sizeof(dest_socket_addr.sin_zero));

    dest_socket_addr.sin_family = AF_INET;

    dest_socket_addr.sin_addr.s_addr = dest_ip;

    dest_socket_addr.sin_port = htons(0);

    icmp_packet = (ICMP_PACKET *)malloc(sizeof(ICMP_PACKET));

    if (icmp_packet == NULL)

    {

        ERROR_LOG(DOWNLOAD_LOG, "malloc error.\n");

        return ret;

    }

    memset(icmp_packet, 0, sizeof(ICMP_PACKET));

    icmp_header = &icmp_packet->icmp_header;

    icmp_header->icmp_type = 8;

    icmp_header->icmp_code = 0;

    icmp_header->icmp_id = getpid();

    icmp_packet->icmp_sum_flag = generation_checksum((u_int16_t *)icmp_packet, sizeof(ICMP_PACKET));

    DEBUG_LOG(DOWNLOAD_LOG, "PING %s (%s).\n", hostName, inet_ntoa(*((struct in_addr*)&dest_ip)));

    snprintf(res_buffer, buffer_len, "PING %s (%s).\n", hostName, inet_ntoa(*((struct in_addr*)&dest_ip)));

    thread_data.send_flag  = 1;

    thread_data.sockaddr    = &dest_socket_addr;

    thread_data.fd          = client_fd;

    thread_data.buffer      = res_buffer;

    thread_data.times      = times;

    thread_data.icmp_packet = icmp_packet;

    ret = pthread_create(&send_pid, NULL, send_imcp, (void *)&thread_data);

    if (ret < 0)

    {

        ERROR_LOG(DOWNLOAD_LOG, "pthread create error: %s\n", strerror(errno));

        goto FAIL_EXIT;

    }

    ret = pthread_create(&recv_pid, NULL, recv_imcp, (void *)&thread_data);

    if (ret < 0)

    {

        ERROR_LOG(DOWNLOAD_LOG, "pthread create error: %s\n", strerror(errno));

        pthread_detach(send_pid);

        goto FAIL_EXIT;

    }

    pthread_join(send_pid, NULL);

    pthread_join(recv_pid, NULL);

    FAIL_EXIT:

    if (icmp_packet != NULL)

    {

        free(icmp_packet);

        icmp_packet = NULL;

    }

    if (client_fd >= 0)

    {

        close(client_fd);

        client_fd = -1;

    }

    return ret;

}

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 214,444评论 6 496
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 91,421评论 3 389
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 160,036评论 0 349
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 57,363评论 1 288
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 66,460评论 6 386
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 50,502评论 1 292
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 39,511评论 3 412
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,280评论 0 270
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 44,736评论 1 307
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,014评论 2 328
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,190评论 1 342
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 34,848评论 5 338
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 40,531评论 3 322
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,159评论 0 21
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,411评论 1 268
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,067评论 2 365
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,078评论 2 352

推荐阅读更多精彩内容