Ip address get

From Teknologisk videncenter
Revision as of 10:45, 23 March 2024 by Heth (talk | contribs) (c)
Jump to: navigation, search

c

#include <stdio.h>
#include <unistd.h>
#include <string.h> /* for strncpy */

#include <sys/types.h>
#include <sys/socket.h>
#include <sys/ioctl.h>
#include <netinet/in.h>
#include <net/if.h>
#include <arpa/inet.h>
#include <getopt.h>

int main(int argc, char *argv[]) {
 int fd;
 struct ifreq ifr;

  if (argc != 2) {
          fprintf(stderr,"Usage: %s interface\n",argv[0]);
          return(1);
  }

 fd = socket(AF_INET, SOCK_DGRAM, 0);

 /* I want to get an IPv4 IP address */
 ifr.ifr_addr.sa_family = AF_INET;

 /* I want IP address attached to interfacename in argv[1] */
 strncpy(ifr.ifr_name, argv[1], IFNAMSIZ-1);

 ioctl(fd, SIOCGIFADDR, &ifr);

 close(fd);

 /* display result */
 printf("%s\n", inet_ntoa(((struct sockaddr_in *)&ifr.ifr_addr)->sin_addr));

 return 0;
}

Python

import netifaces

interface='eth0'
ipv4=2          # netifaces index for ipv4

def get_ipv4(iface):
    interface_list = netifaces.interfaces()

    for i in interface_list:
        if iface == i:
            addresses=netifaces.ifaddresses(iface)
            if ipv4 in addresses:
                return(addresses[ipv4][0]['addr'])
            else:
                return("No IPv4 address")