2

我正在使用以下代码在某个端口连接到服务器,这些端口作为命令行参数提供......

#include <stdio.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <errno.h>
#include <stdlib.h>
#include <strings.h>

int main(int argc,char *argv[])
{
   struct sockaddr_in serverAddr;
   int clientSocketFd ;
   char buffer[1024];

 if((clientSocketFd = socket(AF_INET, SOCK_STREAM, 0))==-1)
    perror("socket");

//get the server IP address and PORT
bzero(&serverAddr, sizeof serverAddr);
printf("ip address :- %s\n",argv[1]);
inet_pton(AF_INET, argv[1], &(serverAddr.sin_addr));
serverAddr.sin_family=AF_INET;
serverAddr.sin_port = atoi(argv[2]);

printf("PORT :- %d\n",serverAddr.sin_port);
//connect to server
if(connect(clientSocketFd,(struct sockaddr *) &serverAddr, sizeof(serverAddr)) == -1)
    perror("connect");

printf("Connecting to the server %s on port %s \n",argv[1],argv[2]);

while (1)
{
    //receive incoming data
    if(recv(clientSocketFd, buffer,1023, 0)==-1)
    {
    printf("buffer : %s\n" ,buffer);
    printf("Received from Server : %s \n",buffer);
        break;
    }


}
close(clientSocketFd);

}

但在客户端,它显示“连接:连接被拒绝”......

如果我使用telnet,那么它显示已连接,但无法通过上面的client.c代码连接,请帮助

另外我将允许的最大挂起连接数更改为 100 ,然后问题也没有解决...... :( ...help plz

4

1 回答 1

10

您连接到错误的端口。改变:

serverAddr.sin_port = atoi(argv[2]);

到:

serverAddr.sin_port = htons(atoi(argv[2]));

把这些结构想象成用来与另一个星球交流,在那里他们以不同的方式写下他们的数字。你必须在你写数字的方式和他们写数字的方式之间来回转换,否则你会胡说八道。

The htons function converts ports numbers from the way your computer stores them to the way they are used on the network. The ntohs function converts port numbers from the way they are used on the network to the way your computer stores them. Socket addresses are in network byte order.

于 2013-01-08T12:12:07.150 回答