用visual studio2022软件并且使用c语言写个完整的代码,完成实现类似ping命令的功能
时间: 2024-12-14 22:26:08 浏览: 3
在Visual Studio 2022中使用C语言编写一个简单的ping命令模拟程序并不复杂,我们可以利用`sys/socket.h`库来进行套接字操作。以下是实现的基本步骤和一个简化的代码示例:
```c
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <unistd.h>
#define BUFFER_SIZE 512
int main(int argc, char *argv[]) {
if (argc != 2) {
printf("Usage: ping [IP address]\n");
return -1;
}
struct sockaddr_in server_addr;
int sock = socket(AF_INET, SOCK_DGRAM, 0);
if (sock == -1) {
perror("Error creating socket");
return -1;
}
// Convert IP string to binary format
if (inet_pton(AF_INET, argv[1], &server_addr.sin_addr) <= 0) {
perror("Invalid IP address");
close(sock);
return -1;
}
server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(80); // Any non-privileged port can be used here for demonstration
char message[BUFFER_SIZE] = "Pong from client\n";
ssize_t bytes_sent;
do {
bytes_sent = sendto(sock, message, strlen(message), 0, (struct sockaddr *)&server_addr, sizeof(server_addr));
if (bytes_sent > 0) {
char response[BUFFER_SIZE];
memset(response, 0, sizeof(response));
bytes_sent = recvfrom(sock, response, BUFFER_SIZE - 1, 0, NULL, NULL);
if (bytes_sent > 0) {
response[bytes_sent] = '\0';
printf("Received reply: %s\n", response);
} else {
perror("Error receiving reply");
}
} else {
perror("Error sending request");
}
} while (bytes_sent > 0);
close(sock);
return 0;
}
阅读全文