TheoretiCAL
TheoretiCAL

Reputation: 20571

Socket Client always connects to localhost

I have a problem where my client always seems to connect to localhost(127.0.0.1) even though I'm passing it another 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 always results in a connection to localhost, even though argv[1] is 139.130.4.5 and portnum is 80

Upvotes: 0

Views: 546

Answers (2)

4pie0
4pie0

Reputation: 29744

In memcpy() function:

#include <string.h>
void *memcpy(void *dest, const void *src, size_t n);

The first argument is destination, the second is the source, so 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);
     // ^ as Adam pointed out, no (char*) here

Upvotes: 3

Adam Rosenfield
Adam Rosenfield

Reputation: 400462

You have the arguments to memcpy(3) backwards. It should be memcpy(dest, source, len):

memcpy(&serv_addr.sin_addr.s_addr, server->h_addr, server->h_length);

Also, you shouldn't be casting to char * in the calls to memcpy() and memset(), since they take void* as arguments, and any pointer type can be implicitly converted to void* without a cast. The cast just clutters up the code and could hide a potential bug (like trying to pass in a non-pointer type).

Upvotes: 2

Related Questions