1

Here's my problem:

I'm trying to fill a socket address struct with the appropriate information so that I can use it in a program the handles communication between a server and a client. This is part of the server code. The problem is that it segfaults. When I run gdb, it says that the seg fault occurs when I assign AF_INET to the sin_family attribute for the servaddr struct.

code:

servaddr->sin_family = (short)(AF_INET); 

I can't seem to figure out why this occurs.

Here's the full code:

// Function Prototypes
struct sockaddr_in* getServerInfo(char[]);

int main()
{

    char hostname[MAXHOSTNAMELEN];
    struct sockaddr_in* servaddr = getServerInfo(hostname);

 return 0;
} // End main

struct sockaddr_in* getServerInfo(char hostname[])
{

    struct sockaddr_in* servaddr = malloc((size_t)sizeof(struct sockaddr_in));
    gethostname(hostname, 32);
    struct hostent *hostptr;
    hostptr = gethostbyname(hostname);

    memset((void *) &servaddr, 0, (size_t)sizeof(servaddr));
    servaddr->sin_family = (short)(AF_INET);
    memcpy((void *)& servaddr->sin_addr, (void *) hostptr->h_addr, hostptr->h_length);
    servaddr->sin_port = htons((u_short)8000);

    return servaddr;
}
4

1 回答 1

1

你的错误在这里:

memset((void *) &servaddr, 0, (size_t)sizeof(servaddr));

改为这样做:

memset((void *) servaddr, 0, (size_t)sizeof(*servaddr));

否则,您将 servaddr 的指针归零(即将其变为 NULL)。当您尝试使用它时,它会爆炸。

同样,您需要更改 memcpy 调用。

于 2013-01-21T01:08:04.307 回答