Results 1 to 2 of 2

Thread: How to get your ip ..

  1. #1
    SG Stud ColdFusion's Avatar
    Join Date
    Oct 2000
    Vancouver, BC

    How to get your ip ..


    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.


  2. #2
    Regular Member
    Join Date
    Aug 1999
    Depends on the operating system. But, in Linux something like this should do it:

    #include <iostream>  // cout
    #include <cstring>   // memset(), strncpy()
    #ifdef __cplusplus
    extern "C" {
    #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
    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 ) {
        return 3;
      }  // End if
      // Close the socket...
      // 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)...


Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts