0

我用c语言编写了我的tcp客户端。tcp服务器是用java编写的。问题是我设置了客户端使用的特定端口,但我连接到另一个端口而不是我设置的端口的服务器。为什么会发生这种情况?

连接函数是:

int CONECT_T0_SERVER(void)
    {
    int iSetOption = 1;

    sock_descriptor = socket(AF_INET, SOCK_STREAM, 0);

    setsockopt(sock_descriptor, SOL_SOCKET, SO_REUSEADDR, (char*)&iSetOption,
            sizeof(iSetOption));

    if(sock_descriptor < 0)
      printf("Failed creating socket\n");

    memset(&sa_loc, 0, sizeof(struct sockaddr_in));
    sa_loc.sin_family = AF_INET;
    sa_loc.sin_port = htons(10002);
    sa_loc.sin_addr.s_addr = inet_addr("10.10.1.30");

    ret = bind(sock_descriptor, (struct sockaddr *)&sa_loc, sizeof(struct sockaddr));


    bzero((char *)&serv_addr, sizeof(serv_addr));

    server = gethostbyname("10.10.1.120");
   // server = gethostbyname("192.168.123.103");
    //server = gethostbyname("127.0.0.1");

    if(server == NULL)
    {
        printf("Failed finding server name\n");
        return -1;
    }

    serv_addr.sin_family = AF_INET;
    memcpy((char *) &(serv_addr.sin_addr.s_addr), (char *)(server->h_addr), server-  >h_length);

    serv_addr.sin_port = htons(10000);
    //serv_addr.sin_port = htons(1234);

    if (connect(sock_descriptor, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) < 0)
    {
        printf("Failed to connect to server\n");
        return -1;
    }

    else
    {
        printf("Connected successfully \n");
    }
    return 0;
    }

服务器端口为 10000,客户端端口设置为 10002,但是当我连接到服务器时,客户端端口不同。

4

1 回答 1

2

传递给的大小bind()是错误的。

假设sa_loc声明为:

struct sockaddr_in sa_loc;

应为:

ret = bind(sock_descriptor, (struct sockaddr *) &sa_loc, sizeof(struct sockaddr_in));

甚至更好(更不容易出错):

 ret = bind(sock_descriptor, (struct sockaddr *) &sa_loc, sizeof(sa_loc));

顺便说一句:它在调用connect().

于 2013-08-21T12:20:59.920 回答