socket not bind()ing - 参数无效

时间:2015-04-23 00:31:18

标签: c linux

晚上好,   对于踢腿和咯咯笑声,我试着用* NIX套接字和TCP / IP。现在,为了起步,我只是尝试在两个端点上创建套接字和来回的基本文本聊天程序。现在,在我开始运行之前,我遇到了一个无效的争论':

user@user-VirtualBox:~/sockets$ ./socket
sock=3
s_->sin_family = 2
s_->sin_port = 3879
s_->sin_addr.s_addr = 0
sockfd = 3
s_->sin_family = 2
s_->sin_port = 3879
s_->sin_addr.s_addr = 0
Socket bind error: Invalid argument
sizeof(s_) = 8

以下代码。所以,根据我的理解,INADDR_ANY应该是255.255.225.255 = 0; AF_INET是2;和sin_port,好吧,我已经向后看和向前看了二进制文件,我不确定我是否理解9000在主机顺序中是如何从9000以3879表示的,但是假设它不是问题。另外,由于1是stdout而2是stderr,我假设上面的任何内容都是动态分配的,因此3应该适用于套接字文件描述符。

#include <stdio.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <string.h>
#include <errno.h>
void setSocket(struct sockaddr_in* s_){
    s_->sin_family=AF_INET;
    s_->sin_port=htons(9999);
    s_->sin_addr.s_addr=INADDR_ANY;
    memset(&(s_->sin_zero), '\0', 8);
    printf("s_->sin_family = %i\n", s_->sin_family);    
    printf("s_->sin_port = %i\n", s_->sin_port);
    printf("s_->sin_addr.s_addr= %i\n", s_->sin_addr.s_addr);
}

void createSocket(int *sock){
    if ((*sock = socket(AF_INET, SOCK_STREAM, 0)) == -1){
        fprintf(stderr, "Socket creation error: %s\n", strerror(errno));
        exit(1);
    }
    printf("sock = %i\n", *sock);
    fflush(stdout);
}

void bindSocket(int sock, struct sockaddr_in* s_){
    printf("s_->sin_family = %i\n",s_->sin_family);
    printf("s_->sin_port = %i\n",s_->sin_port);
    printf("s_->sin_addr.s_addr = %i\n",s_->sin_addr.s_addr);
    if((bind(sock, (struct sockaddr*)s_, (socklen_t)sizeof(s_))) == -1){
        fprintf(stderr, "Socket bind error: %s\n", strerror(errno));
    }
    printf("sizeof(s_) = %lu\n", sizeof(s_));
}

int main(int argc, char* argv[]){
    int sockfd;
    struct sockaddr_in socket_;
    createSocket(&sockfd);
    setSocket(&socket_);
    printf("sockfd = %i\n", sockfd);
    fflush(stdout);
    bindSocket(sockfd, &socket_);
    exit(0);
}

1 个答案:

答案 0 :(得分:0)

我认为问题是

  

的sizeof()   在你的bind()中......'s_'是一个指针,所以它的sizeof(可能)是4 ...   你需要取消引用它:

if((bind(sock, (struct sockaddr*)s_, (socklen_t)sizeof(*s_))) == -1){
    fprintf(stderr, "Socket bind error: %s\n", strerror(errno));
}