C - 套接字编程客户端服务器 - 主机名上的连接

时间:2015-12-03 15:33:06

标签: c sockets

在我的服务器上,我现在有了这个代码:

      #define h_addr h_addr_list[0]

      serverAddr.sin_port = htons(port);

      /* Set IP address to localhost */
      hostname[1023] = "\0";
      gethostname(hostname, 1023);
      printf("HostName: %s\n", hostname); // this one prints correctly

      my_hostent = gethostbyname(hostname);
      printf("Host: %s\n", my_hostent->h_addr);
      printf("IP: %c\n", inet_ntoa(my_hostent->h_addr));
      serverAddr.sin_addr.s_addr = *hostname;

在客户端,我知道您必须将主机编写为参数,因此我可以在此示例中编写-h www.abc.com我自己说我的服务器也在www.abc.com上托管,但是他们此刻从不沟通,但是当我打印主机名时,它说的是相同的。

客户端代码。

#define h_addr h_addr_list[0]

struct hostent *server;

server = gethostbyname(hostname);
serverAddr.sin_addr.s_addr = server->h_addr;

“hostname”变量是程序启动时的参数。

这是客户端错误:

 warning: assignment makes integer from pointer without a cast
   serverAddr.sin_addr.s_addr = server->h_addr;

这是服务器错误:

server.c:42:18: warning: assignment makes integer from pointer without a cast
   hostname[1023] = "\0";
                  ^
server.c:43:3: warning: implicit declaration of function ‘gethostname’ [-Wimplicit-function-declaration]
   gethostname(hostname, 1023);
   ^
server.c:48:3: warning: implicit declaration of function ‘inet_ntoa’ [-Wimplicit-function-declaration]
   printf("IP: %c\n", inet_ntoa(lol->h_addr));
   ^

任何人都可以看到我的套接字故障并将它们连接在一起吗?

目前,如果我将双方都设置为INADDR_ANY,它将工作并自动连接,

2 个答案:

答案 0 :(得分:3)

问题是serverAddr.sin_addr.s_addruint32_tserver->h_addrchar *

h_addr字段实际上是h_addr_list[0]的别名,其中h_addr_listchar **。该字段指向一组地址结构,可以是struct in_addrstruct in6_addr

对于gethostbyname,它将是struct in_addr,因此您需要将其强制转换为serverAddr.sin_addr而不是serverAddr.sin_addr.s_addr

serverAddr.sin_addr = *((struct in_addr *)server->h_addr);

这不是一个有效的声明:

hostname[1023] = "\0";

你想要的是这个:

char hostname[1023] = {0};

这会将整个数组初始化为零。

答案 1 :(得分:3)

0xFFFF

VALUE是一个字符串文字,表示两个0x00FF的数组,均为零。在赋值语句中,与大多数其他上下文一样,表达式将转换为指向第一个char的指针。显然,server.c:42:18: warning: assignment makes integer from pointer without a cast hostname[1023] = "\0"; ^ "\0"数组或const char,因此hostname是代表单个char的左值。您正在尝试为该char指定一个char指针。

你想要一个字面文字:

char *

或等同于

hostname[1023]
char

您未能hostname[1023] = '\0'; 声明函数hostname[1023] = 0; server.c:43:3: warning: implicit declaration of function ‘gethostname’ [-Wimplicit-function-declaration] gethostname(hostname, 1023); ^ server.c:48:3: warning: implicit declaration of function ‘inet_ntoa’ [-Wimplicit-function-declaration] printf("IP: %c\n", inet_ntoa(lol->h_addr)); ^ 的标头。在POSIX系统上,那些将是

#include
相关问题