Linux Network Programming

From Teknologisk videncenter
Revision as of 10:37, 3 November 2023 by Heth (talk | contribs) (Created page with "=Find IP address of an interface= <source lang=c> #include <stdio.h> #include <unistd.h> #include <string.h> for strncpy: #include <sys/types.h> #include <sys/socket.h> #...")
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search

Find IP address of an interface

#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;
}