inaddr_any例子
时间: 2024-01-29 10:03:31 浏览: 69
INADDR_ANY是一个特殊的IP地址,用于表示任意IP地址。在网络编程中经常使用此常量作为socket绑定的地址,以监听所有可用的网络接口。
以下是一个使用INADDR_ANY的例子:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#define PORT 8080
int main() {
int sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd < 0) {
perror("socket creation failed");
exit(EXIT_FAILURE);
}
struct sockaddr_in servaddr = {0};
servaddr.sin_family = AF_INET;
servaddr.sin_addr.s_addr = INADDR_ANY;
servaddr.sin_port = htons(PORT);
if (bind(sockfd, (const struct sockaddr *)&servaddr, sizeof(servaddr)) < 0) {
perror("bind failed");
exit(EXIT_FAILURE);
}
if (listen(sockfd, 5) < 0) {
perror("listen failed");
exit(EXIT_FAILURE);
}
printf("Server listening on port %d\n", PORT);
while (1) {
int newsockfd = accept(sockfd, NULL, NULL);
if (newsockfd < 0) {
perror("accept failed");
exit(EXIT_FAILURE);
}
char buffer[1024] = {0};
int valread = read(newsockfd, buffer, sizeof(buffer));
printf("Received message: %s\n", buffer);
const char *reply = "Hello from server";
write(newsockfd, reply, strlen(reply));
close(newsockfd);
}
close(sockfd);
return 0;
}
```
在此示例中,我们创建了一个TCP socket,并使用INADDR_ANY绑定到所有可用的网络接口。然后我们监听连接请求,并在每个新连接上发送“Hello from server”消息。
阅读全文