#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <netinet/ip_icmp.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <unistd.h>
#include <sys/time.h>
#define PACKET_SIZE 64 // ICMP报文大小
#define MAX_WAIT_TIME 2 // 最大等待时间(秒)
// 计算校验和
unsigned short calculateChecksum(unsigned short *addr, int len) {
unsigned int sum = 0;
while (len > 1) {
sum += *addr++;
len -= 2;
}
if (len == 1) {
sum += *(unsigned char *)addr;
}
sum = (sum >> 16) + (sum & 0xFFFF);
sum += (sum >> 16);
return (unsigned short)(~sum);
}
// 发送ICMP Echo请求
void sendICMPEchoRequest(int sockfd, struct sockaddr_in *dest_addr, int seq) {
struct icmp send_pkt;
int pkt_size = sizeof(struct icmp);
memset(&send_pkt, 0, pkt_size); // 清空结构体
send_pkt.icmp_type = ICMP_ECHO;
send_pkt.icmp_code = 0;
send_pkt.icmp_id = getpid();
send_pkt.icmp_seq = seq;
send_pkt.icmp_cksum = calculateChecksum((unsigned short *)&send_pkt, pkt_size);
// 发送报文
ssize_t bytes_sent = sendto(sockfd, &send_pkt, pkt_size, 0, (struct sockaddr *)dest_addr, sizeof(struct sockaddr));
if (bytes_sent <= 0) {
perror("sendto");
exit(1);
}
}
// 接收ICMP Echo响应
void receiveICMPEchoResponse(int sockfd, struct sockaddr_in *src_addr) {
char recv_buf[PACKET_SIZE];
struct sockaddr_in from_addr;
socklen_t from_addr_len = sizeof(from_addr);
ssize_t bytes_received = recvfrom(sockfd, recv_buf, sizeof(recv_buf), 0, (struct sockaddr *)&from_addr, &from_addr_len);
if (bytes_received <= 0) {
perror("recvfrom");
exit(1);
}
struct ip *ip_hdr = (struct ip *)recv_buf;
struct icmp *icmp_hdr = (struct icmp *)(recv_buf + (ip_hdr->ip_hl << 2));
if (icmp_hdr->icmp_type == ICMP_ECHOREPLY) {
printf("Reply from %s: seq=%d\n", inet_ntoa(from_addr.sin_addr), icmp_hdr->icmp_seq);
}
}
int main(int argc, char **argv) {
if (argc != 2) {
printf("Usage: %s <host>\n", argv[0]);
exit(1);
}
const char *host = argv[1];
struct hostent *hostent = gethostbyname(host);
if (!hostent) {
printf("Couldn't resolve host: %s\n", host);
exit(1);
}
struct sockaddr_in dest_addr;
memset(&dest_addr, 0, sizeof(dest_addr));
dest_addr.sin_family = AF_INET;
dest_addr.sin_addr = *((struct in_addr *)hostent->h_addr);
// 创建原始套接字
int sockfd = socket(AF_INET, SOCK_RAW, IPPROTO_ICMP);
if (sockfd < 0) {
perror("socket");
exit(1);
}
int seq = 0;
while (seq < 4) {
sendICMPEchoRequest(sockfd, &dest_addr, seq);
receiveICMPEchoResponse(sockfd, &dest_addr);
seq++;
sleep(1);
}
close(sockfd);
return 0;
}
C语言实现ping
于 2023-12-28 17:20:31 首次发布