c localhost拒绝TCP套接字连接

时间:2016-03-22 11:56:37

标签: c sockets tcp localhost client-server

我正在尝试在localhost中创建一个客户端/服务器程序,但客户端无法连接到服务器,我不知道我做错了什么。

我试图调试程序,所有参数似乎都没问题。服务器确实绑定,连接,监听和接受。

客户端代码出现connect: Invalid argument错误。客户端(我使用./client localhost从控制台调用客户端):

#include <netinet/in.h>
#include <netdb.h>
#include <string.h>
#include <stdio.h>
#include <errno.h>

int main(int argc, char * argv[])
{
    int cd;
    struct hostent *hp;
    struct sockaddr_in s_ain;
    unsigned char byte;

    hp = gethostbyname(argv[1]);
    bzero((char *)&s_ain, sizeof(s_ain));
    s_ain.sin_family = AF_INET;
    memcpy(&(s_ain.sin_addr),  hp->h_addr, hp->h_length);
    s_ain.sin_port = htons(1025);

    cd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
    if( connect(cd, (struct sockaddr*) &s_ain, sizeof(s_ain) == -1) ) {
        fprintf(stderr, "connect: %s\n", strerror(errno));
        return -1;
    }       

    printf("%s\n", "IT WORKS!");
    close(cd);
    return 0;
}

服务器:

#include <netinet/in.h>
#include <netdb.h>
#include <string.h>
#include <stdio.h>

int main(void)
{
    int sd, cd;
    socklen_t size;     
    unsigned char byte;
    struct sockaddr_in s_ain, c_ain;    

    sd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);

    bzero((char *)&s_ain, sizeof(s_ain));
    s_ain.sin_family = AF_INET;s_ain.sin_family = AF_INET;
    s_ain.sin_addr.s_addr = INADDR_ANY;
    s_ain.sin_port = htons(1025);

    if(bind(sd, (struct sockaddr *)&s_ain, sizeof(s_ain)) == -1) {
        fprintf(stderr, "%s\n", "err bind");
        return -1;
    }

    if(listen(sd, 5) == -1) {
        fprintf(stderr, "%s\n", "err listen");
        return -1;
    }

    while(1) {
        size = sizeof(c_ain);
        cd = accept(sd, (struct sockaddr *)&c_ain, &size);
        printf("%s\n", "IT WORKS !");
    }
}

2 个答案:

答案 0 :(得分:5)

您的示例中有错字或

if( connect(cd, (struct sockaddr*) &s_ain, sizeof(s_ain) == -1) ) {
    fprintf(stderr, "%s\n", "err connect");
    return -1;
}

括号错误。目前,您将connectsocklen_t addrlen称为0。它应该读

if( connect(cd, (struct sockaddr*) &s_ain, sizeof(s_ain)) == -1) {
    fprintf(stderr, "%s\n", "err connect");
    return -1;
}

答案 1 :(得分:0)

server.c中的一些修复程序

#include <netinet/in.h> // fix
#include <sys/types.h>
#include <netdb.h>
#include <string.h>
#include <stdio.h>

int main(void)
{
    int sd, cd;
    unsigned char byte;
    struct sockaddr_in c_ain;

    sd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);

    bzero((char *)&c_ain, sizeof(c_ain));
    c_ain.sin_family = AF_INET;
    c_ain.sin_addr.s_addr = INADDR_ANY;
    c_ain.sin_port = htons(1025);

    bind(sd, (struct sockaddr *)&c_ain, sizeof(c_ain));
    listen(sd, 5);

    struct sockaddr_in t_ain;
    while(1) {
       int size = sizeof(t_ain); // < fix
       cd = accept(sd, (struct sockaddr *)&t_ain, (socklen_t*)&size); // < fix
       printf("%s\n", "IT WORKS !");
    }
}

另外,为了测试服务器,你可以使用telnet:

  

telnet 127.0.0.1 1025