Closed. This question is off-topic。它当前不接受答案。
想改善这个问题吗? Update the question,因此它是on-topic,用于堆栈溢出。
4年前关闭。
这是我编写的用于创建套接字并将其绑定到地址和端口的代码:
在这里,我期望输出为:
但是结果是“无法绑定到套接字”。
这可能是什么原因?
想改善这个问题吗? Update the question,因此它是on-topic,用于堆栈溢出。
4年前关闭。
这是我编写的用于创建套接字并将其绑定到地址和端口的代码:
#include <stdio.h>
#include <sys/types.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <strings.h>
#include <netdb.h>
int main(int argc, char *argv[])
{
const char APPRESSMESSAGE[] = "APRESS,For Profesionals By Professional!\n";
int SimpleSocket = 0;
int SimplePort = 0;
if (argc != 2)
{
fprintf(stderr, "USAGE: %s <port>\n", argv[0]);
exit(1);
}
SimpleSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (SimpleSocket == -1)
{
fprintf(stderr, "Could not create the socket !\n");
exit(2);
}
else
{
fprintf(stdout, "socket created\n");
}
SimplePort = atoi(argv[1]);
struct sockaddr_in SimpleServer;
bzero(&SimpleServer, sizeof(SimpleServer));
SimpleServer.sin_family = AF_INET;
SimpleServer.sin_addr.s_addr = htonl(INADDR_ANY);
SimpleServer.sin_port = htons(SimplePort);
int return_status;
return_status = bind(SimpleSocket, (struct sockaddr *)&SimpleServer, sizeof(SimpleServer));
if (return_status == 0)
{
fprintf(stdout, "bind completed\n");
}
else
{
fprintf(stderr, "could not bind to socket\n");
close(SimpleSocket);
exit(1);
}
return 0;
}
在这里,我期望输出为:
socket created
bind completed.
但是结果是“无法绑定到套接字”。
这可能是什么原因?
最佳答案
结果是“无法绑定到套接字”。这可能是什么原因?
从man bind
引用(在Linux系统上),可能会出现一些错误(Unix套接字的错误更多,但这是一个TCP套接字):
ERRORS EACCES The address is protected, and the user is not the superuser. EADDRINUSE The given address is already in use. EBADF sockfd is not a valid descriptor. EINVAL The socket is already bound to an address. ENOTSOCK sockfd is a descriptor for a file, not a socket.
You could reduce the number of possibilities to investigate significantly by checking the value of errno
, or by simply using a call to perror
:
if (bind(SimpleSocket,(struct sockaddr *)&SimpleServer,sizeof(SimpleServer)) == 0) {
fprintf(stdout,"bind completed\n");
}
else {
perror("Could not bind to socket");
close(SimpleSocket);
exit(1);
}
关于c - 绑定(bind)在我的C程序中不起作用,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/31630363/