BSD套接字在连接时无效参数

时间:2011-07-14 22:24:39

标签: c++ connection client-server sockets invalid-argument

当我尝试将客户端连接到服务器时,我一直收到无效的参数错误。网上有几个线程说这可能发生在addrlen不正确的时候,但我尝试在计算长度之后将其更改为字面值,但这不起作用。我也试过strlen()而没有运气。无论如何,相关代码 -

服务器 -

struct sockaddr name;
int main(int agrc, char** argv) {

    int sock, new_sd, adrlen;   //sock is this socket, new_sd is connection socket

    name.sa_family = AF_INET;
    strcpy(name.sa_data, "127.0.0.1");
    adrlen = strlen(name.sa_data) + sizeof(name.sa_family);

    //make socket
    sock = socket(AF_INET, SOCK_STREAM, 0);

    if (sock < 0) {
        printf("\nBind error %m", errno);
        exit(1);
    }  

    //unlink and bind
    unlink("127.0.0.1");
    if(bind (sock, &name, adrlen) < 0)
        printf("\nBind error %m", errno);

    //listen
    if(listen(sock, 5) < 0)
        printf("\nListen error %m", errno);

    //accept
    new_sd = accept(sock, &name, (socklen_t*)&adrlen);
    if( new_sd < 0) {
        printf("\nAccept error %m", errno);
        exit(1);
    }

客户 -

int main(int agrc, char** argv) {

    int sock, new_sd, adrlen;

    sock = socket(AF_INET, SOCK_STREAM, 0);

    if (sock < 0) {
        printf("\nserver socket failure %m", errno);
        exit(1);
    }

    //stuff for server socket
    name.sa_family = AF_INET;
    strcpy(name.sa_data, "127.0.0.1");
    adrlen = strlen(name.sa_data) + sizeof(name.sa_family);

    cout<<"\nadrlen: "<<adrlen<<"\n";
    if(connect(sock, &name, adrlen) < 0) {
        printf("\nclient connection failure %m", errno);
        exit(1);
    }

我没有看到任何可能出错的东西,但我想我可能只是忽略了某些东西或者没有意识到某些东西。任何帮助表示赞赏。

2 个答案:

答案 0 :(得分:1)

strcpy(name.sa_data, "127.0.0.1");

真的?地址应该是32位IPv4地址,而不是字符串。

这是AF_INET的结构(来自here):

// IPv4 AF_INET sockets:

struct sockaddr_in {
    short            sin_family;   // e.g. AF_INET, AF_INET6
    unsigned short   sin_port;     // e.g. htons(3490)
    struct in_addr   sin_addr;     // see struct in_addr, below
    char             sin_zero[8];  // zero this if you want to
};

struct in_addr {
    unsigned long s_addr;          // load with inet_pton()
};

答案 1 :(得分:0)

你的大问题是完全误解了sockaddr结构!

首先使用sockaddr_in

然后您将编写更多如下代码:

sockaddr_in sai;
sai.sin_family = AF_INET;
sai.sin_port   = htons( 12345 );  /// Or whatever port you wish to use.
inet_aton("127.0.0.1", &sai.sin_addr.s_addr);

注意:htons将短值从主机转换为网络格式。主机可能是大端或小端。网络是大端。