报错warning: implicit declaration of function ‘inet_ntoa’ [-Wimplicit-function-declaration] 49 | printf("客户端 %s:%d 已连接\n", inet_ntoa(client_addr.sin_addr), ntohs(client_addr.sin_port)); | ^~~~~~~~~ 1.c:49:28: warning: format ‘%s’ expects argument of type ‘char *’, but argument 2 has type ‘int’ [-Wformat=]
时间: 2024-02-02 08:05:03 浏览: 35
这个警告提示说,在你的代码中使用了一个未声明的函数 `inet_ntoa()`,所以编译器无法确定该函数的返回类型和参数类型,因此会给出这个警告。同时,还有一个格式化字符串错误,因为 `%s` 格式符需要一个字符串作为参数,但是你传递给它的是一个整数,所以编译器会给出第二个警告。
你需要包含一个头文件 `<arpa/inet.h>` 来声明 `inet_ntoa()` 函数,这个头文件包含了一些网络编程相关的函数和定义。同时,你需要使用 `%d` 格式符来打印一个整数,而不是 `%s` 格式符。
修复代码如下:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <unistd.h>
int main(int argc, char *argv[]) {
// 创建 socket
int server_fd = socket(AF_INET, SOCK_STREAM, 0);
if (server_fd == -1) {
perror("创建 socket 失败");
exit(EXIT_FAILURE);
}
// 准备地址和端口
struct sockaddr_in server_addr = {0};
server_addr.sin_family = AF_INET;
server_addr.sin_addr.s_addr = INADDR_ANY;
server_addr.sin_port = htons(8888);
// 绑定地址和端口
if (bind(server_fd, (struct sockaddr *)&server_addr, sizeof(server_addr)) == -1) {
perror("绑定地址和端口失败");
exit(EXIT_FAILURE);
}
// 监听端口
if (listen(server_fd, 5) == -1) {
perror("监听端口失败");
exit(EXIT_FAILURE);
}
// 接受客户端连接
struct sockaddr_in client_addr = {0};
socklen_t client_addr_len = sizeof(client_addr);
int client_fd = accept(server_fd, (struct sockaddr *)&client_addr, &client_addr_len);
if (client_fd == -1) {
perror("接受客户端连接失败");
exit(EXIT_FAILURE);
}
// 打印客户端地址和端口
char client_ip[20];
inet_ntop(AF_INET, &client_addr.sin_addr, client_ip, sizeof(client_ip));
printf("客户端 %s:%d 已连接\n", client_ip, ntohs(client_addr.sin_port));
// 关闭连接
close(client_fd);
close(server_fd);
return 0;
}
```