我真的不知道我做错了什么。我包括了所有好的图书馆。并在我的 VPS 和本地 Ubuntu 安装上对其进行了测试。我还查找了可以正常工作的同一程序的其他代码。但我不断收到“错误:无法将 Internet 地址绑定(bind)到套接字方法”消息。 这是我用 C 代码编写的 TCP 服务器:
#include <stdio.h>
#include <strings.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <unistd.h>
#include <netinet/in.h>
#include <stdlib.h>
//Enter The Port and the Ip Address here.
#define PORT 666
#define ADRESS 0
//Enter the amount of Maximum Poeple entering the server.
#define NUMBER_OF_CONNECTIONS 8
int main(){
int sockfd, newsockfd, portno = 666, clilen;
char message[1024];
struct sockaddr_in serv_addr, cli_addr;
int n;
sockfd = (AF_INET, SOCK_STREAM, 0);
if (sockfd < 0){
printf("ERROR: could not create server-socket.\n");
exit(1);
}
bzero((char *) &serv_addr, sizeof(serv_addr));
// Declaring the port.
//portno = 666;
// Declaring the type of connection. (internet connection)
serv_addr.sin_family = AF_INET;
// Declaring the IP.
serv_addr.sin_addr.s_addr = INADDR_ANY;
// Declaring the Port.
serv_addr.sin_port = htons(portno);
// Binding the Socket?
if (bind(sockfd, (struct sockaddr *) &serv_addr, sizeof(serv_addr)) < 0){
printf("ERROR: could not bind internet address to the socket method.\n");
exit(1);
}
// Entering "Listen Mode".
listen(sockfd, NUMBER_OF_CONNECTIONS);
clilen = sizeof(cli_addr);
// Creating a New Socket for the client.
newsockfd = accept(sockfd, (struct sockaddr *) &cli_addr, &clilen);
if (newsockfd < 0){
printf("ERROR: could not accept connection.\n");
exit(1);
}
//Clearing the message-buffer.
bzero(message,1024);
// Reading the message.
n = read(newsockfd,message,1023);
if (n < 0){
printf("ERROR: could not read message.\n");
}
printf("Message: %s\n",message);
n = write(newsockfd, "I got your message.", 18);
if (n < 0)
{
printf("ERROR: sending to client.\n");
}
return 0;
}
最佳答案
问题是这一行:
sockfd = (AF_INET, SOCK_STREAM, 0);
它是有效的,右侧的表达式计算为 0
(请参阅 C 中的逗号运算符)。
现在对 bind()
的调用被放置在 fd 0 上,它通常是一个(伪)终端。这不可能成功。
解决方法是:
sockfd = socket(AF_INET, SOCK_STREAM, 0);
关于c - 编程 C : getting error when binding address and port to socket,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41600750/