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.