2024年4月17日发(作者:)
linux下ping命令的实现源码
// ping.c
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#define BUFSIZE 1500
#define MAX_WAIT_TIME 5
#define MAX_NO_PACKETS 3
// Type of the ICMP header
typedef struct icmphdr
unsigned char type;
unsigned char code;
// Type of the ICMP
// Code of the ICMP
unsigned short checksum; // Checksum of the ICMP
unsigned short id; // ID of the ICMP
unsigned short sequence; // Sequence of the ICMP
} icmphdr;
// IP header's structure
struct iphdr
unsigned char h_verlen;
unsigned char tos;
// length of the header
// Type of service
unsigned short total_len; // Total length of packet
unsigned short ident; // Unique identifier
unsigned short frag_and_flags; // Flags
unsigned char ttl; // Time to live
// Protocol (TCP, UDP etc)
unsigned char proto;
unsigned short checksum; // IP checksum
unsigned int sourceIP;
unsigned int destIP;
};
// Source IP
// Destination IP
unsigned short checksum (unsigned short *addr, int len);
int pack(char *buf, int s, int seq);
int send_packet(int sockfd, struct sockaddr_in *addr, char
*sendpacket);
int recv_packet(int sockfd, char *buf, struct sockaddr_in
*addr);
int main(int argc, char *argv[])
struct hostent *host;
struct sockaddr_in addr;
int sockfd, size = 50 * 1024, cnt = MAX_NO_PACKETS, i;
char sendpacket[BUFSIZE], recvpacket[BUFSIZE];
struct sockaddr_in from;
int fromlen = sizeof(from);
// Check for the arguments
if (argc != 2)
printf("Usage: %s hostname/IP addressn", argv[0]);
exit(1);
}
// socket
sockfd = socket(AF_INET, SOCK_RAW, IPPROTO_ICMP);
if (sockfd < 0)
printf("Socket creating errorn");
exit(1);
}
// Get the hostname
if ((host = gethostbyname(argv[1])) == NULL)
printf("Hostname errorn");
exit(1);
}
// Make address structure
bzero(&addr, sizeof(addr));
_family = AF_INET;
_addr = *(struct in_addr *)host->h_addr;
_port = htons(0);
// set socket buffer size
if (setsockopt(sockfd, SOL_SOCKET, SO_RCVBUF, &size,
sizeof(size)) == -1)
printf("Set socket buffer size errorn");
exit(1);
}
// Send the ICMP packet
for (i = 0; i < cnt; i++)


发布评论