【C言語】pingを自作する方法を解説

目次から探す

完成したサンプルコード

上記の手順を組み合わせて作成したサンプルコードは以下の通りです。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/socket.h>
#include <netinet/ip.h>
#include <netinet/ip_icmp.h>
#include <netdb.h>
#include <arpa/inet.h>
int main() {
    int sockfd;
    sockfd = socket(AF_INET, SOCK_RAW, IPPROTO_ICMP);
    if (sockfd < 0) {
        perror("socket");
        exit(1);
    }
    struct icmphdr icmp;
    memset(&icmp, 0, sizeof(struct icmphdr));
    icmp.type = ICMP_ECHO;
    icmp.code = 0;
    icmp.checksum = 0;
    icmp.un.echo.id = getpid();
    icmp.un.echo.sequence = 1;
    struct sockaddr_in dest_addr;
    memset(&dest_addr, 0, sizeof(struct sockaddr_in));
    dest_addr.sin_family = AF_INET;
    dest_addr.sin_addr.s_addr = inet_addr("127.0.0.1"); // 送信先のIPアドレスを指定Specify destination IP address대상 IP 주소 지정Angiv destinationens IP-adresseAnge destinationens IP-adressGeef het doel-IP-adres opEspecifique o endereço IP de destinoGeben Sie die Ziel-IP-Adresse anSpécifier l'adresse IP de destinationEspecificar la dirección IP de destinoSpecificare l'indirizzo IP di destinazione
    int send_result = sendto(sockfd, &icmp, sizeof(struct icmphdr), 0, (struct sockaddr*)&dest_addr, sizeof(struct sockaddr_in));
    if (send_result < 0) {
        perror("sendto");
        exit(1);
    }
    struct sockaddr_in recv_addr;
    socklen_t recv_addr_len = sizeof(struct sockaddr_in);
    unsigned char recv_buf[1024];
    int recv_result = recvfrom(sockfd, recv_buf, sizeof(recv_buf), 0, (struct sockaddr*)&recv_addr, &recv_addr_len);
    if (recv_result < 0) {
        perror("recvfrom");
        exit(1);
    }
    struct iphdr* ip = (struct iphdr*)recv_buf;
    struct icmphdr* icmp_reply = (struct icmphdr*)(recv_buf + (ip->ihl * 4));
    if (icmp_reply->type == ICMP_ECHOREPLY) {
        printf("Ping succeeded!\n");
    } else {
        printf("Ping failed!\n");
    }
    return 0;
}

以上がC言語でのping送信プログラムの作成手順と完成したサンプルコードです。

このプログラムを実行すると、指定したIPアドレスに対してpingを送信し、応答を解析します。

1 2
この記事のページ一覧
  1. 現在のページ
目次から探す