Display hostname and IP address in C

4

Here is a good way to determine the hostname and IP address of the local machine in C.

You first have to grab the hostname with gethostname().

Take the hostname and use it to grab the hostent struct with gethostbyname().

Finally you have to take the hostent that is returned and pull out the IP address. It is in network byte order, so you have to convert it to a string with inet_ntoa().

Put all this together into a working programs.

Share.
  • kumar

    dude, this program seg faults. could you post some working code please?

  • kumar

    my bad, i was using it incorrectly. it works, thanks.

    • Ryan

      Glad I could help!

  • Dave

    My Good God,

    “My bad” is the best apology for such an ansinine comment made by Kumar? What a world.
    Thanks for the code sir! Benefited us greatly.