converting host to ip by sockaddr_in gethostname etc

前端 未结 2 2020
名媛妹妹
名媛妹妹 2020-12-28 11:14

i need help converting hostname to ip and inserting to sockaddr_in->sin_addr to be able assign to char. For example i input: localhost and it gives me 127.0.0.1

I fo

2条回答
  •  眼角桃花
    2020-12-28 11:28

    Try something like this:

      struct hostent        *he;
      struct sockaddr_in  server;
      int                 socket;
    
      const char hostname[] = "localhost";
    
      /* resolve hostname */
      if ( (he = gethostbyname(hostname) ) == NULL ) {
          exit(1); /* error */
      }
    
      /* copy the network address to sockaddr_in structure */
      memcpy(&server.sin_addr, he->h_addr_list[0], he->h_length);
      server.sin_family = AF_INET;
      server.sin_port = htons(1337);
    
      /* and now  you can connect */
      if ( connect(socket, (struct sockaddr *)&server, sizeof(server) ) {
          exit(1); /* error */
      }
    

    I wrote this code straight from my memory so I cannot guarantee that it works but I am pretty sure it should be OK.

提交回复
热议问题