简体   繁体   English

在 Linux 的套接字编程中无法将 in_addr 转换为 Unsigned Int

[英]Cannot Convert in_addr to Unsigned Int in Socket Programming for Linux

I'm building a reverse echo server in TCP using c++.我正在使用 c++ 在 TCP 中构建反向回显服务器。

My problem occurs when I run my client.我的问题发生在我运行客户端时。

When I compile my client.cpp, I get this error:当我编译我的 client.cpp 时,我得到这个错误:

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?我错过了什么吗?

You are trying to assign a whole in_addr struct instance to a single integer. That will not work.您正在尝试将整个in_addr结构实例分配给单个 integer。那是行不通的。

The sockaddr_in::sin_addr member is an in_addr struct, and the in_addr::s_addr member is the actual IP address. sockaddr_in::sin_addr成员是一个in_addr结构, in_addr::s_addr成员是实际的 IP 地址。 Just drop the s_addr part to assign the whole in_addr struct as-is:只需删除s_addr部分即可按原样分配整个in_addr结构:

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.否则,您可以将memcpy() (或者,在您的示例中为memmove() )将in_addr结构作为一个整体放入sin_addr成员中。 You are trying to copy/move to its s_addr member instead, so just drop that:您正在尝试复制/移动到其s_addr成员,所以只需删除它:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM