1
votes

I'm trying to make a simple socket client (using debian 6 and g++ compiler) and when I'm calling "connect" function, it returns error code 22 - Invalid argument. Tell me, what am I doing wrong, please.

I've read the man page for this function and it says that the 3 arguments must be as followed: int, struct sockaddr* and socklen_t.

My code is:

  int                   serverPort;
  u_long                serverHost;
  struct sockaddr_in    serverAddress;
  socklen_t             serverAddressLength;
  int                   clientSocket;

  serverPort = 44444;
  serverHost = inet_addr ( "88.198.237.65" );
  serverAddress.sin_family = AF_INET;
  serverAddress.sin_port =  htons ( serverPort );
  serverAddress.sin_addr.s_addr = htons ( serverHost );
  serverAddressLength = sizeof ( serverAddress );

  clientSocket = socket ( AF_INET , SOCK_STREAM , 0 );

  connect ( clientSocket , (sockaddr*)&serverAddress , serverAddressLength )
1

1 Answers

2
votes
  serverAddress.sin_addr.s_addr = htons ( serverHost );

An IPv4 address is a long, not a short, so htons is right out. The data is in network byte order already anyway, so no conversion is needed.

The inet_addr() function converts the Internet host address cp from IPv4 numbers-and-dots notation into binary data in network byte order.

Also:

 char                  serverHost;

How's it supposed to fit in a char?