绑定无效的参数

时间:2013-12-06 19:24:40

标签: c sockets network-programming

我正在玩unix套接字。代码编译正常,但我在执行

时收到以下消息
Invalid argument

这是我使用的代码。我认为这很简单

#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <stdio.h>
#include <stdlib.h>

#define PORT 7000


int main(){
    int socket_desc;
    struct sockaddr_in address;

    socket_desc = socket(AF_INET, SOCK_STREAM, 0);

    if(socket_desc == -1)
        perror("Create socket");

    /* type of socket created in socket() */
    address.sin_family = AF_INET;
    address.sin_addr.s_addr = INADDR_ANY;
    /* set port */
    address.sin_port = htons(PORT);

    while(1) {
        /* bind the socket to the port specified above */
        if(bind(socket_desc,(struct sockaddr *)&address, sizeof(address)) < 0) {
            perror("Error");
            exit(-1);
        }
    }

    return 0;
}

1 个答案:

答案 0 :(得分:3)

问题是你试图绑定不止一次 - while(1)循环是什么?

while(1) {
    /* bind the socket to the port specified above */
    if(bind(socket_desc,(struct sockaddr *)&address, sizeof(address)) < 0) {
        perror("Error");
        exit(-1);
    }
}

bind()第一次成功,在随后的调用中,EINVAL失败,这意味着(来自man 2 bind):

  

[EINVAL] 套接字已绑定到某个地址,并且该协议不支持绑定到新地址。或者,插座可能已经                           关闭。

作为旁注,在传递它之前将sockaddr归零可能是个好主意:

#include <string.h>
/* ... */

memset(&address, 0, sizeof(address));

address.sin_family = AF_INET;
address.sin_addr.s_addr = INADDR_ANY;
address.sin_port = htons(PORT);