我正在尝试编写一个 C 程序来侦听我机器上的端口。我遇到了一个奇怪的错误。
每当我尝试将套接字绑定到固定 IP(127.0.0.1
或我的实际 IP)时,都会出现"bind failed: Cannot assign requested address"
错误。但是,当我将INADDR_ANY
绑定作为要绑定的地址传递给绑定时,它可以工作。
这是我仅有的两个 IP,所以 0.0.0.0 不可能因为我有其他一些可用的 IP 地址而工作。
这是代码:
#include<sys/types.h>
#include<stdio.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<errno.h>
#include<stdlib.h>
#include<string.h>
int main()
{
int port = 1234; /* port number */
int rqst; /* socket accepting the request */
socklen_t alen; /* length of address structure */
struct sockaddr_in my_addr; /* address of this service */
struct sockaddr_in client_addr; /* client's address */
int sockoptval = 1;
int svc;
/* create a TCP/IP socket */
if ((svc = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
perror("cannot create socket");
exit(1);
}
/* allow immediate reuse of the port */
setsockopt(svc, SOL_SOCKET, SO_REUSEADDR, &sockoptval, sizeof(int));
/* bind the socket to our source address */
memset((char*)&my_addr, 0, sizeof(my_addr)); /* 0 out the structure */
my_addr.sin_family = AF_INET; /* address family */
my_addr.sin_port = htons(port);
//my_addr.sin_addr.s_addr = htonl(INADDR_ANY); /* Works! */
my_addr.sin_addr.s_addr = htonl(inet_addr("127.0.0.1")); /* Fails! */
if (bind(svc, (struct sockaddr *)&my_addr, sizeof(my_addr)) < 0) {
perror("bind failed");
exit(1);
}
printf("Listening on %d\n", my_addr.sin_addr.s_addr);
/* set the socket for listening (queue backlog of 5) */
if (listen(svc, 5) < 0) {
perror("listen failed");
exit(1);
}
/* loop, accepting connection requests */
for (;;) {
while ((rqst = accept(svc, (struct sockaddr *)&client_addr, &alen)) < 0) {
/* we may break out of accept if the system call */
/* was interrupted. In this case, loop back and */
/* try again */
if ((errno != ECHILD) && (errno != ERESTART) && (errno != EINTR)) {
perror("accept failed");
exit(1);
}
}
/* the socket for this accepted connection is rqst */
}
}