我正在尝试制作IPv6服务器,但我遇到套接字绑定问题。 “无法绑定套接字”
所有代码:
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <stdbool.h>
int main(int argc, char *argv[]) {
int server_port = 8877;
struct sockaddr_in6 server_address;
memset(&server_address, 0, sizeof(server_address));
server_address.sin6_family = AF_INET6;
server_address.sin6_port = htons(server_port);
server_address.sin6_addr = in6addr_any;
int sockfd;
if (sockfd = socket(AF_INET6, SOCK_STREAM, 0) < 0) {
printf("could not create listen socket\n");
return 1;
}
if (bind(sockfd, (struct sockaddr *)&server_address, sizeof(server_address)) < 0) {
printf("could not bind socket\n");
return 1;
}
int numberOfClients = 1;
if (listen(sockfd, numberOfClients) < 0) {
printf("could not open socket for listening\n");
return 1;
}
struct sockaddr_in client_address;
int client_len = 0;
char buff4[INET_ADDRSTRLEN];
while (1) {
int sock;
if ((sock =
accept(sock, (struct sockaddr *)&client_address,
0)) < 0) {
printf("could not open a socket to accept data\n");
return 1;
}
//printf("client connected with ip address: %s\n", inet_ntop(AF_INET, &(client_address.sin_addr), buff4, INET_ADDRSTRLEN));
int n = 0;
int len = 0, maxlen = 100;
char buffer[maxlen];
char *pbuffer = buffer;
printf("client connected with ip address: %s\n",
inet_ntoa(client_address.sin_addr));
while ((n = recv(sock, pbuffer, maxlen, 0)) > 0) {
pbuffer += n;
maxlen -= n;
len += n;
printf("received: '%s'\n", buffer);
// echo received content back
send(sock, buffer, len, 0);
}
close(sock);
}
close(sockfd);
return 0;
}
答案 0 :(得分:2)
这里的问题是您的操作顺序。
你写过:
if (sockfd = socket(AF_INET6, SOCK_STREAM, 0) < 0) {
您希望将socket()
的返回值分配给sockfd
。但相反,它将该返回值与0进行比较,并且该值是否小于0是实际存储在sockfd中的内容。
在比较之前,您应该使用一对额外的括号来明确表示您想要进行分配,然后才进行比较:
if ((sockfd = socket(AF_INET6, SOCK_STREAM, 0)) < 0) {
更好的是,通过首先分配然后单独比较,使代码更加明显,使代码更易于维护。
sockfd = socket(AF_INET6, SOCK_STREAM, 0);
if (sockfd < 0) {