编程C:将地址和端口绑定到套接字时出错

时间:2017-01-11 21:10:54

标签: c sockets tcp binding server

我真的不知道自己做错了什么。我包括了所有好的库。并在我的VPS和本地Ubuntu安装上进行了测试。另外,我查找了相同程序的其他代码。但我一直得到“错误:无法将互联网地址绑定到套接字方法”消息。 这是我的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;
}

3 个答案:

答案 0 :(得分:4)

问题在于这一行:

 sockfd = (AF_INET, SOCK_STREAM, 0);

它是有效的,右侧的表达式求值为0(参见C中的逗号运算符)。

现在对bind()的调用放在fd 0上,fd 0通常是(伪)终端。这不可能成功。

解决方案是:

 sockfd = socket(AF_INET, SOCK_STREAM, 0);

答案 1 :(得分:3)

尝试更换:

sockfd = (AF_INET, SOCK_STREAM, 0);

sockfd = socket(AF_INET, SOCK_STREAM, 0);

答案 2 :(得分:0)

这对我有所帮助:

当然将sockfd = (AF_INET, SOCK_STREAM, 0);更改为sockfd = socket(AF_INET, SOCK_STREAM, 0);,由于某种原因,我必须使用port under 1024的root权限。

有人可以解释一下原因吗?

感谢您的帮助:D