0

i would like to creat a simple TCP client with sockaddr_in pointer.

#include <iostream>
#include <sys/types.h> 
#include <sys/socket.h>
#include <netdb.h>
#include <stdlib.h>
#include <unistd.h>

#include <arpa/inet.h>
#include <netinet/in.h>
#include <cstdlib>

#include <errno.h>  /* errno */
#include <string.h> /* strerror() */

using namespace std;

int creeSock();
struct sockaddr_in* configConnect(int dSock, char* adresseIP, int numPort);

int main(int argc, char *argv[])
{
    if (argc < 3){
        exit(1);
    } 

    int dSock = creeSock();
    struct sockaddr_in* aD = configConnect(dSock, argv[1], atoi(argv[2]));

    close(dSock);
    return 0;
}


int creeSock(){
    int dSock;
    if( (dSock = socket(PF_INET, SOCK_STREAM, 0)) == -1){
        perror("Erreur lors de la création de la socket ");
        exit(errno);
    }

    return dSock;
}

struct sockaddr_in* configConnect(int dSock, char* adresseIP, int numPort){
    struct sockaddr_in* ad = (struct sockaddr_in*)malloc(sizeof(struct sockaddr_in));

    if(inet_pton(AF_INET, adresseIP, &(ad->sin_addr)) <= 0){
        perror("config error");
        exit(errno);
    }

    ad->sin_port = htons(numPort);

    if (connect(dSock,(struct sockaddr*)ad, sizeof(*ad)) == -1){
        cout<<errno;
        perror("Error connect ");
        exit(errno);
    }


    return ad;
}

No compilation error (g++ -std=c++11 client.cpp) On execution: ./a.out 127.0.0.1 42000

Error connect : Invalid argument

My old code works on same server when sockaddr_in is not a pointer

Thank you in advance.

FL0Nn
  • 53
  • 1
  • 7
  • Can you please *show* the declarations or definitions of `IP` and `PORT`? Because right now the types you say they are makes no sense with the code you use. Better yet, please try to create a [Minimal, Complete, and Verifiable Example](http://stackoverflow.com/help/mcve) and show us. – Some programmer dude Mar 30 '17 at 10:32
  • Also please see [this question about casting the result of `malloc`](http://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc). – Some programmer dude Mar 30 '17 at 10:34
  • I use a function `struct sockaddr_in* configConnect(int dSock, char* adresseIP, int numPort)` , i just simplify with no function. My function is call like that `struct sockaddr_in* aD = configConnect(dSock, argv[1], atoi(argv[2]));` with argv[1] IP and argv[2] PORT – FL0Nn Mar 30 '17 at 10:38
  • @FlorianNovellon that contradicts your question! best to update it with a [mcve] so we're all on the same page and can answer your question – Chris Turner Mar 30 '17 at 10:50

1 Answers1

0

You're not setting the sin_family element of the structure.

if(inet_pton(AF_INET, IP, &(ad->sin_addr)) <= 0){
        perror("Error config ");
        exit(errno);
}

ad->sin_port = htons(PORT);

// need to set sin_family, too
ad->sin_family = AF_INET;
Andrew Henle
  • 32,625
  • 3
  • 24
  • 56