top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

How to get the IP-Address of the machine in C/C++?

+1 vote
1,019 views

Without system command :)

posted Aug 23, 2014 by anonymous

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button
I am just guessing, using pcap library function.

2 Answers

+1 vote

To get the IP Address of the system, you need interface name (i.e eth0 or wlan0 etc) and you have to call
"ioctl()" with flag "SIOCGIFADDR".

Here I am providing a c program which will print the ip address of the given interface.

#include <stdio.h>
#include <sys/ioctl.h>
#include <net/if.h>
#include <arpa/inet.h>
#include <stdlib.h>
#include <string.h>

#define IF_NAME "wlan0"   //Change this as per your interface name.

int main()
{
    int sock, ret;
    struct ifreq ifr;

    sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_IP);
    if (-1 == sock) {
        return 0;
    }

    memset(&ifr, 0, sizeof(ifr));
    strncpy(ifr.ifr_name, IF_NAME, sizeof(ifr.ifr_name));

    ret = ioctl(sock, SIOCGIFADDR, &ifr);
    if (ret) {
        goto error_sock;
    }

    struct sockaddr_in* ipaddr = (struct sockaddr_in*)&ifr.ifr_addr;

    printf("IP address : %s\n", inet_ntoa(ipaddr->sin_addr));

error_sock:
    close(sock);
    return 0;

} 

You can also use
getifaddrs() //see the man page for more info.

answer Aug 23, 2014 by Arshad Khan
+1 vote

Try this, works for me.

int main() {
        FILE * fp = popen("ifconfig", "r");
        if (fp) {
                char *p=NULL, *e; size_t n;
                while ((getline(&p, &n, fp) > 0) && p) {
                   if (p = strstr(p, "inet ")) {
                        p+=5;
                        if (p = strchr(p, ':')) {
                            ++p;
                            if (e = strchr(p, ' ')) {
                                 *e='\0';
                                 printf("%s\n", p);
                            }
                        }
                   }
              }
        }
        pclose(fp);
}

Credit: StackOverflow

answer Aug 25, 2014 by Salil Agrawal
It will print the ip address of all the active interface.
Yes that's correct :), good catch
Similar Questions
+1 vote

I want a JAVA program. That gets the website name from the user and prints the IP Address of that website.

+3 votes

Any opensource code would be a great help :)

...