Search code examples
ciphost

converting host to ip by sockaddr_in gethostname etc


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 found code, but I dont know why it gives me wrong numbers

//---
#include <sys/types.h>
#include <netinet/in.h>
#include <string.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <errno.h>
#include <stdlib.h>
#include <time.h>
#include <sys/fcntl.h>
#include <netdb.h>
//---

///CZY WPISANO HOST

        struct in_addr inaddr;
        inaddr.s_addr = inet_addr(argv[1]);
        if( inaddr.s_addr == INADDR_NONE) //if sHost is name and not IP
        {
            struct hostent* phostent = gethostbyname( argv[1]);
            if( phostent == 0)
                bail("gethostbyname()");

            if( sizeof(inaddr) != phostent->h_length)
                bail("problem z inaddr"); // error something wrong,

            puts(argv[1]);
            inaddr.s_addr = *((unsigned long*) phostent->h_addr);

            //strdup( inet_ntoa(inaddr));
            srvr_addr = inet_ntoa(adr_srvr.sin_addr);
            puts(srvr_addr);
        }

I also wrote own code but i dont know how transfer from sockaddr to sockaddr_in data:

///CZY WPISANO HOST
    if(argv[1][0]>=(char)'a' && argv[1][0]<=(char)'Z')
    {
        struct hostent *hent;
        hent = gethostbyname(argv[1]);
        adr_srvr.sin_addr =  (struct in_addr*)hent->h_addr_list;

    }

adr_srvr is a char* type


Solution

  • 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.