c - 收到HTTP请求时如何获取客户端的名称?

标签 c http sockets network-programming

我正在用 C 语言编写一个基本的代理服务器。

我想通过名称或 IP 来识别我正在接收请求的服务器/计算机。

如何做到这一点?我不确定从哪里获取信息。

这是我的连接代码:

  unsigned short port = atoi(argv[1]); /* port number to listen on */

  struct sockaddr_in server;
  server.sin_family = PF_INET;
  server.sin_addr.s_addr = INADDR_ANY;
  server.sin_port = htons( port );
                    /* host-to-network-short() convert to big endian */
  int len = sizeof( server );

  if ( bind( sock, (struct sockaddr *)&server, len ) < 0 )
  {
    perror( "bind() failed" );
    return EXIT_FAILURE;
  }

  /* activate the socket as a listener */
  listen( sock, 5 );   /* 5 is number of backlogged waiting client requests */
  //printf( "Listener socket created and bound to port %d on fd %d\n", port, sock );

  struct sockaddr_in client;

  while ( 1 )
  {
   // printf( "Blocked on accept()\n" );
    unsigned int fromlen;
    int newsock = accept( sock, (struct sockaddr *)&client, &fromlen );
                  /* accept() blocks */
    //printf( "Accepted client connection\n" );

    char buffer[5000];
    int n = read( newsock, buffer, 4999 );
    if ( n < 1 )
    {
      perror("Read() failed.\n");
    }
    else
    {
      buffer[n] = '\0';
      //printf( "Rcvd message from client: \n\n----\n\n%s\n\n----\n\n", buffer );
    }

最佳答案

以下是检索 IP 和主机名的方法:

struct sockaddr_in client;
[...]
 int newsock = accept( sock, (struct sockaddr *)&client, &fromlen );
printf("Client accepted: %s \n", inet_ntoa(client.sin_addr));  

// And the host name
struct hostent *hostName;
struct in_addr ipv4addr;

inet_pton(AF_INET, inet_ntoa(client.sin_addr), &ipv4addr);
hostName = gethostbyaddr(&ipv4addr, sizeof ipv4addr, AF_INET);
printf("Host name: %s\n", hostName->h_name);

关于c - 收到HTTP请求时如何获取客户端的名称?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10236204/

相关文章:

ruby - 如何通过 ruby​​ UDPSocket 类发送原始十六进制数据?

用于主机代码的 CUDA 编译器宏

c - 从文件加载列

http - 为非文本媒体类型发送带有 Content-Type header 的字符集参数绝对错误吗?

c# - C#异步套接字: Is this thread-safe and correctly done?

python - 如何捕获Python中的任何套接字错误?

c - 访问结构对象时出现段错误

无法通过 openssl 以与 crypt、mkpasswd 或 openssl 通过 cmdline 相同的格式获取密码哈希

javascript - 如何使用 XMLHttpRequest() 和 Javascript 处理 POST 请求错误

http - 在 go 中设置 http 处理程序