c++ - Socket Client always connects to localhost -
i have problem client seems connect localhost(127.0.0.1) though i'm passing address. consider: $ ./client 139.130.4.5 80
if ( (sockfd = socket(af_inet, sock_stream, 0)) == -1 ){ error("opening socket"); } if ( (server = gethostbyname(argv[1])) == null) { fprintf(stderr,"error, no such host\n"); close(sockfd); exit(0); } memset((char *) &serv_addr, 0, sizeof(serv_addr)); serv_addr.sin_family = af_inet; memcpy((char *)server->h_addr, (char *)&serv_addr.sin_addr.s_addr, server->h_length); serv_addr.sin_port = htons(portnum); if (connect(sockfd,(struct sockaddr *) &serv_addr,sizeof(serv_addr)) == -1){ error("connect", sockfd); }
this results in connection localhost, though argv[1]
139.130.4.5 , portnum
80
in memcpy() function:
#include <string.h> void *memcpy(void *dest, const void *src, size_t n);
the first argument destination, second source, instead of
memcpy((char *)server->h_addr, (char *)&serv_addr.sin_addr.s_addr, server->h_length);
you should write
memcpy( &serv_addr.sin_addr.s_addr, server->h_addr, server->h_length); // ^ adam pointed out, no (char*) here
Comments
Post a Comment