如何在C程序中添加新功能?

时间:2019-07-17 14:24:11

标签: c

我打算使用GetDomin()在客户端和服务器之间建立连接 功能,以使客户端获取服务器IP并响应客户端。

示例:客户端发送192.xxx.xxx.xx服务器Google

//client 
const char* data_to_send = "Gangadhar Hi Shaktimaan hai";
send(sock, data_to_send, strlen(data_to_send), 0);

// echo
int n = 0;
int len = 0, maxlen = 100;
char buffer[maxlen];
char* pbuffer = buffer;

// remain   open until the server is close 
while ((n = recv(sock, pbuffer, maxlen, 0)) > 0) {
   pbuffer += n;
   maxlen -= n;
   len += n;
   buffer[len] = '\0';
   printf("received: '%s'\n", buffer);
}

//server
while (true) {
   // socket
   socklen_t sock;

   if ((sock = accept(listen_sock, (struct sockaddr *)&client_address,
       &client_address_len)) < 0) {
          printf("could not open a socket to accept data\n");
          return 1;
    }

int n = 0;
int len = 0, maxlen = 100;
char buffer[maxlen];
char *pbuffer = buffer;
printf("client connected with ip address: %s\n",  
inet_ntoa(client_address.sin_addr));

// 
while ((n = recv(sock, pbuffer, maxlen, 0)) > 0) {
   pbuffer += n;
   maxlen -= n;
   len += n;
   printf("received: '%s'\n", buffer);

   // echo data to the client 
   send(sock, buffer, len, 0);
}

0 个答案:

没有答案