How to get your ip ..

General software, Operating Systems, and Programming discussion.
Everything from software questions, OSes, simple HTML to scripting languages, Perl, PHP, Python, MySQL, VB, C++ etc.
Post Reply
User avatar
ColdFusion
Posts: 3542
Joined: Mon Oct 30, 2000 12:00 am
Location: Vancouver, BC

How to get your ip ..

Post by ColdFusion »

Hey,

Not to sure on how to get my ip in c++, i know it has somethign to do with opening a socket and grabing the ip, but im just learning and really have no clue how to even use sockets lol.

Thanks
Stu
Regular Member
Posts: 341
Joined: Tue Aug 10, 1999 12:00 am

Post by Stu »

Depends on the operating system. But, in Linux something like this should do it:

Code: Select all


#include <iostream>  // cout
#include <cstring>   // memset(), strncpy()

#ifdef __cplusplus
extern "C" {
#endif

#include <unistd.h>         // close()
#include <sys/ioctl.h>      // ioctl()
#include <linux/sockios.h>  // SIOCGIFADDR
#include <sys/socket.h>     // socket()
#include <net/if.h>         // struct ifreq
#include <arpa/inet.h>      // inet_ntoa()

#ifdef __cplusplus
};
#endif

using namespace std;

int main(void) {

  struct ifreq        ifr;
  struct sockaddr_in *local_addr;
  int                 fd;

  // Open the socket...
  if ( (fd = socket(AF_INET, SOCK_DGRAM, 0)) == -1)
    return 2;

  // Zero out the receiving structure...
  memset(&ifr, 0, sizeof(struct ifreq));

  // Set the device name...
  strncpy(ifr.ifr_name, "eth0", IF_NAMESIZE);

  // Get the device info...
  if ( ioctl(fd, SIOCGIFADDR, &ifr) == -1 ) {

    close(fd);
    return 3;

  }  // End if

  // Close the socket...
  close(fd);

  // Cast to an easy to convert type (not the safest
  // way to go, but this is just something I'm
  // throwing together)...
  local_addr = (struct sockaddr_in *)&ifr.ifr_addr;

  // Print the IP address for eth0...
  cout << "eth0: "
       << inet_ntoa(local_addr->sin_addr)
       << endl;

  return 0;

}  // End main()

As for Windows, you'll have to get that off someone else (I don't do windows)...
Post Reply