簡體   English   中英

C-套接字編程客戶端服務器-主機名上的連接

[英]C - socket programming client server - connection on host name

在我的服務器上,我現在有以下代碼:

      #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;

“主機名”變量是程序啟動時的參數。

這是客戶端錯誤:

 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,它將可以正常工作並自動連接,

問題是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而不是serverAddr.sin_addr.s_addr

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

這不是有效的聲明:

hostname[1023] = "\0";

您想要的是:

char hostname[1023] = {0};

這會將整個數組初始化為零。

 server.c:42:18: warning: assignment makes integer from pointer without a cast hostname[1023] = "\\0"; ^ 

"\\0"是一個字符串文字,它表示兩個const char的數組,兩者均為零。 與大多數其他上下文一樣,在您的賦值語句中,該表達式將轉換為指向第一個字符的指針。 顯然, hostname是一個char數組或char * ,因此hostname[1023]是一個表示單個char的左值。 您正在嘗試將char指針分配給該char。

您需要一個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)); ^ 

您未能#include聲明函數gethostname()inet_ntoa()的標頭。 在POSIX系統上,這些將是

#include <unistd.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM