您好,登錄后才能下訂單哦!
在C++中,處理ICMP消息通常需要使用原始套接字(raw socket)
#include <iostream>
#include <sys/socket.h>
#include <netinet/ip.h>
#include <netinet/icmp.h>
#include <unistd.h>
#include <cstring>
#define ICMP_BUFFER_SIZE 1500
int main(int argc, char *argv[]) {
if (argc != 2) {
std::cerr << "Usage: " << argv[0]<< " <ICMP_message>" << std::endl;
return 1;
}
int sockfd = socket(AF_INET, SOCK_RAW, IPPROTO_ICMP);
if (sockfd < 0) {
perror("socket");
return 1;
}
struct sockaddr_in icmp_addr;
memset(&icmp_addr, 0, sizeof(icmp_addr));
icmp_addr.sin_family = AF_INET;
icmp_addr.sin_port = htons(0);
icmp_addr.sin_addr.s_addr = inet_addr(argv[1]);
struct icmp *icmp_header = (struct icmp *)argv[1];
if (sendto(sockfd, icmp_header, ICMP_BUFFER_SIZE, 0, (struct sockaddr *)&icmp_addr, sizeof(icmp_addr)) < 0) {
perror("sendto");
close(sockfd);
return 1;
}
close(sockfd);
return 0;
}
要編譯此程序,請使用以下命令:
g++ -o icmp_sender icmp_sender.cpp
然后,你可以使用以下命令發送ICMP Echo請求(ping):
sudo ./icmp_sender <destination_ip>
請注意,運行此程序可能需要管理員權限,因為它需要創建原始套接字。
要處理收到的ICMP消息,你需要編寫一個循環來接收數據包,然后解析ICMP頭。這涉及到檢查ICMP類型和代碼字段,以及獲取相關的數據包信息(如源IP和目標IP)。這里有一個簡單的示例,展示了如何接收和解析ICMP Echo請求(ping響應):
#include <iostream>
#include <sys/socket.h>
#include <netinet/ip.h>
#include <netinet/icmp.h>
#include <unistd.h>
#include <cstring>
#define BUF_SIZE 1500
int main(int argc, char *argv[]) {
if (argc != 2) {
std::cerr << "Usage: " << argv[0]<< " <port>" << std::endl;
return 1;
}
int sockfd = socket(AF_INET, SOCK_RAW, IPPROTO_ICMP);
if (sockfd < 0) {
perror("socket");
return 1;
}
struct sockaddr_in serv_addr;
memset(&serv_addr, 0, sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
serv_addr.sin_port = htons(atoi(argv[1]));
serv_addr.sin_addr.s_addr = INADDR_ANY;
if (bind(sockfd, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) < 0) {
perror("bind");
close(sockfd);
return 1;
}
struct sockaddr_in from;
socklen_t from_size = sizeof(from);
char buffer[BUF_SIZE];
while (1) {
int n = recvfrom(sockfd, buffer, BUF_SIZE, 0, (struct sockaddr *)&from, &from_size);
if (n < 0) {
perror("recvfrom");
continue;
}
struct icmp *icmp_header = (struct icmp *)(buffer + 20); // Skip Ethernet header
if (icmp_header->icmp_type == ICMP_ECHO && icmp_header->icmp_code == 0) {
std::cout << "Received ICMP Echo reply from " << inet_ntoa(from.sin_addr) << std::endl;
}
}
close(sockfd);
return 0;
}
要編譯此程序,請使用以下命令:
g++ -o icmp_receiver icmp_receiver.cpp
然后,你可以使用以下命令運行此程序并監聽指定的端口:
sudo ./icmp_receiver <port>
請注意,運行此程序可能需要管理員權限,因為它需要創建原始套接字。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。