用c语言实现ping命令
时间: 2023-10-26 20:05:33 浏览: 107
实现ping命令需要使用原始套接字,因此需要root权限。以下是一个简单的ping程序实现:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <errno.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/ip.h>
#include <netinet/ip_icmp.h>
#include <netdb.h>
#include <arpa/inet.h>
#include <signal.h>
#include <time.h>
#define PACKET_SIZE 64
#define MAX_WAIT_TIME 5
#define MAX_NO_PACKETS 3
int sockfd, datalen = 56;
char sendpacket[PACKET_SIZE];
char recvpacket[PACKET_SIZE];
struct sockaddr_in dest_addr;
pid_t pid;
int nsend = 0, nreceived = 0;
struct timeval tvrecv;
void statistics(int signo);
unsigned short cal_chksum(unsigned short *addr, int len);
int pack(int pack_no);
void send_packet(void);
void recv_packet(void);
int main(int argc, char *argv[])
{
struct hostent *host;
struct protoent *protocol;
unsigned long inaddr = 0l;
int waittime = MAX_WAIT_TIME;
int size = 50 * 1024;
if(argc < 2) {
printf("Usage: %s hostname/IP address\n", argv[0]);
exit(1);
}
if((protocol = getprotobyname("icmp")) == NULL) {
perror("getprotobyname");
exit(1);
}
if((sockfd = socket(AF_INET, SOCK_RAW, protocol->p_proto)) < 0) {
perror("socket error");
exit(1);
}
setuid(getuid());
setsockopt(sockfd, SOL_SOCKET, SO_RCVBUF, &size, sizeof(size));
bzero(&dest_addr, sizeof(dest_addr));
dest_addr.sin_family = AF_INET;
if(inaddr = inet_addr(argv[1]) == INADDR_NONE) {
if((host = gethostbyname(argv[1])) == NULL) {
perror("gethostbyname error");
exit(1);
}
memcpy((char *)&dest_addr.sin_addr, host->h_addr, host->h_length);
} else {
dest_addr.sin_addr.s_addr = inaddr;
}
pid = getpid();
printf("PING %s (%s): %d bytes data in ICMP packets.\n", argv[1], inet_ntoa(dest_addr.sin_addr), datalen);
signal(SIGALRM, statistics);
while(nsend < MAX_NO_PACKETS) {
nsend++;
send_packet();
recv_packet();
sleep(1);
}
return 0;
}
int pack(int pack_no)
{
int packsize;
struct icmp *icmp;
struct timeval *tval;
icmp = (struct icmp*)sendpacket;
icmp->icmp_type = ICMP_ECHO;
icmp->icmp_code = 0;
icmp->icmp_cksum = 0;
icmp->icmp_seq = pack_no;
icmp->icmp_id = pid;
packsize = 8 + datalen;
tval = (struct timeval*)icmp->icmp_data;
gettimeofday(tval, NULL);
icmp->icmp_cksum = cal_chksum((unsigned short*)icmp, packsize);
return packsize;
}
unsigned short cal_chksum(unsigned short *addr, int len)
{
int nleft = len;
int sum = 0;
unsigned short *w = addr;
unsigned short answer = 0;
while(nleft > 1) {
sum += *w++;
nleft -= 2;
}
if(nleft == 1) {
*(unsigned char *)(&answer) = *(unsigned char *)w;
sum += answer;
}
sum = (sum >> 16) + (sum & 0xFFFF);
sum += (sum >> 16);
answer = ~sum;
return answer;
}
void send_packet(void)
{
int packetsize;
packetsize = pack(nsend);
if(sendto(sockfd, sendpacket, packetsize, 0, (struct sockaddr *)&dest_addr, sizeof(dest_addr)) < 0) {
perror("sendto error");
}
}
void recv_packet(void)
{
int n;
socklen_t fromlen;
extern int errno;
fromlen = sizeof(dest_addr);
alarm(MAX_WAIT_TIME);
while(1) {
if((n = recvfrom(sockfd, recvpacket, sizeof(recvpacket), 0, (struct sockaddr *)&dest_addr, &fromlen)) < 0) {
if(errno == EINTR) {
continue;
}
perror("recvfrom error");
continue;
}
gettimeofday(&tvrecv, NULL);
struct ip *ip = (struct ip *)recvpacket;
struct icmp *icmp = (struct icmp *)(recvpacket + (ip->ip_hl << 2));
if(icmp->icmp_type == ICMP_ECHOREPLY) {
nreceived++;
printf("%d bytes from %s: icmp_seq=%u ttl=%d time=%.2f ms\n",
n, inet_ntoa(dest_addr.sin_addr), icmp->icmp_seq, ip->ip_ttl,
(tvrecv.tv_sec - ((struct timeval *)icmp->icmp_data)->tv_sec) * 1000.0 +
(tvrecv.tv_usec - ((struct timeval *)icmp->icmp_data)->tv_usec) / 1000.0);
}
else if (icmp->icmp_type == ICMP_TIME_EXCEEDED) {
printf(" From %s icmp_seq=%u Time to live exceeded\n", inet_ntoa(dest_addr.sin_addr), icmp->icmp_seq);
}
else {
printf("received packet from %s type %d\n", inet_ntoa(dest_addr.sin_addr), icmp->icmp_type);
}
break;
}
}
void statistics(int signo)
{
printf("\n%d packets transmitted, %d received, %%%d lost\n", nsend, nreceived, (nsend - nreceived) / nsend * 100);
close(sockfd);
exit(1);
}
```
该程序使用了原始套接字实现ICMP协议的包发送和接收。在发送数据包时,程序填充ICMP数据包结构体,计算校验和并发送数据包;在接收数据包时,程序解析IP和ICMP头部,判断接收到的数据包是不是对自己发送的数据包的回应。
注意:由于该程序需要访问网络层,因此需要root权限运行。
阅读全文