Home > Software design >  Cannot Convert in_addr to Unsigned Int in Socket Programming for Linux
Cannot Convert in_addr to Unsigned Int in Socket Programming for Linux

Time:03-18

I'm building a reverse echo server in TCP using c .

My problem occurs when I run my client.

When I compile my client.cpp, I get this error:

error: cannot convert ‘in_addr’ to ‘in_addr_t {aka unsigned int}’ in assignment
  serverAddress.sin_addr.s_addr = *((struct in_addr*)host->h_addr);

This is my code for creating a connection:

serverName = argv[1];
struct sockaddr_in serverAddress;
struct hostent* host;
host = gethostbyname(serverName);

memset(&serverAddress, 0, sizeof(serverAddress));
serverAddress.sin_family = AF_INET;
serverAddress.sin_addr.s_addr = *((struct in_addr*)host->h_addr);
serverAddress.sin_port = htons(serverPort);
memmove(&serverAddress.sin_addr.s_addr, host->h_addr_list[0], host->h_length);

connectValue = connect(clientSocket, (struct sockaddr*)&serverAddress, sizeof(serverAddress));

Am I missing something?

CodePudding user response:

You are trying to assign a whole in_addr struct instance to a single integer. That will not work.

The sockaddr_in::sin_addr member is an in_addr struct, and the in_addr::s_addr member is the actual IP address. Just drop the s_addr part to assign the whole in_addr struct as-is:

serverAddress.sin_addr = *((struct in_addr*)host->h_addr);

Otherwise, you can memcpy() (or, in your example, memmove()) the in_addr struct into the sin_addr member as a whole. You are trying to copy/move to its s_addr member instead, so just drop that:

memcpy(&serverAddress.sin_addr, host->h_addr, host->h_length);
  • Related