我正在尝试编写一个侦听我机器上端口的C程序。 我遇到了一个奇怪的错误。
每当我尝试将套接字绑定到固定的ip(127.0.0.1
或我的实际IP)时,我都会遇到"bind failed: Cannot assign requested address"
错误。
但是,当我将INADDR_ANY
作为要绑定的地址传递给绑定时,它可以正常工作。
这是我拥有的唯一两个IP,所以不能因为我可用的其他IP地址而使0.0.0.0正常工作。
以下是代码:
#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 */
}
}
答案 0 :(得分:7)
函数inet_addr
返回已经按网络顺序的地址:
inet_addr()函数转换来自的Internet主机地址cp 将IPv4数字和点符号表示为网络字节顺序中的二进制数据
请放弃htonl
。