将代码inet_ntoa(client_addr.sin_addr)改为inet_ntop()函数
时间: 2024-01-24 07:03:44 浏览: 119
inet_ntop() 函数能够将网络字节序的二进制IP地址转换为点分十进制格式的字符串IP地址。如果要将代码中的inet_ntoa()函数改为inet_ntop()函数,需要修改以下几点:
1. 在头文件中包含<arpa/inet.h>以使用inet_ntop()函数。
2. 将inet_ntoa(client_addr.sin_addr)替换为inet_ntop(AF_INET, &(client_addr.sin_addr), client_ip, INET_ADDRSTRLEN),其中client_ip是存放字符串IP地址的缓冲区,INET_ADDRSTRLEN是缓冲区大小。
3. 在调用inet_ntop()函数之前,需要将client_ip缓冲区清空,以防止出现未知的字符。
下面是修改后的代码示例:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <netinet/in.h>
#define PORT 8080
int main(int argc, char const *argv[]) {
int server_fd, new_socket, valread;
struct sockaddr_in address;
int opt = 1;
int addrlen = sizeof(address);
char buffer[1024] = {0};
char *hello = "Hello from server";
char client_ip[INET_ADDRSTRLEN];
// Creating socket file descriptor
if ((server_fd = socket(AF_INET, SOCK_STREAM, 0)) == 0) {
perror("socket failed");
exit(EXIT_FAILURE);
}
// Forcefully attaching socket to the port 8080
if (setsockopt(server_fd, SOL_SOCKET, SO_REUSEADDR | SO_REUSEPORT,
&opt, sizeof(opt))) {
perror("setsockopt");
exit(EXIT_FAILURE);
}
address.sin_family = AF_INET;
address.sin_addr.s_addr = INADDR_ANY;
address.sin_port = htons(PORT);
// Forcefully attaching socket to the port 8080
if (bind(server_fd, (struct sockaddr *)&address,
sizeof(address)) < 0) {
perror("bind failed");
exit(EXIT_FAILURE);
}
if (listen(server_fd, 3) < 0) {
perror("listen");
exit(EXIT_FAILURE);
}
if ((new_socket = accept(server_fd, (struct sockaddr *)&address,
(socklen_t *)&addrlen)) < 0) {
perror("accept");
exit(EXIT_FAILURE);
}
// Convert binary IP address to string IP address
memset(client_ip, '\0', INET_ADDRSTRLEN);
inet_ntop(AF_INET, &(address.sin_addr), client_ip, INET_ADDRSTRLEN);
printf("Connection accepted from %s:%d\n", client_ip, ntohs(address.sin_port));
valread = read(new_socket, buffer, 1024);
printf("%s\n", buffer);
send(new_socket, hello, strlen(hello), 0);
printf("Hello message sent\n");
return 0;
}
```
阅读全文