Created
April 29, 2016 05:52
-
-
Save YutaroHayakawa/e2e69cfb9925f7ea9b703b648ec2a00f to your computer and use it in GitHub Desktop.
Get IPv4 address from interface name in FreeBSD
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #include <stdio.h> | |
| #include <stdlib.h> | |
| #include <string.h> | |
| #include <sys/types.h> | |
| #include <netinet/in.h> | |
| #include <net/if.h> | |
| #include <ifaddrs.h> | |
| #define FORMAT_IP4_ADDR "%u.%u.%u.%u" | |
| int get_ip4_addr(const char *ifname, struct in_addr *ipaddr); | |
| int main(void) { | |
| struct in_addr ipaddr; | |
| unsigned char octet[4]; | |
| if(get_ip4_addr("em0", &ipaddr) < 0) { | |
| fprintf(stderr, "get_ip4_addr() failed\n"); | |
| exit(EXIT_FAILURE); | |
| } | |
| memcpy(octet, &(ipaddr.s_addr), sizeof(octet)); | |
| printf("IP4 Address: " FORMAT_IP4_ADDR "\n", | |
| octet[0], octet[1], octet[2], octet[3]); | |
| return 0; | |
| } | |
| int get_ip4_addr(const char *ifname, struct in_addr *ipaddr) | |
| { | |
| struct ifaddrs *ifap; | |
| struct ifaddrs *searcher; | |
| struct sockaddr_in *in_addr; | |
| int ret = 0; | |
| if((ret = getifaddrs(&ifap)) < 0) { | |
| return ret; | |
| } | |
| searcher = ifap; | |
| while(searcher->ifa_next != NULL) { | |
| if(strcmp(searcher->ifa_name, ifname) && | |
| searcher->ifa_addr->sa_family == AF_INET) { | |
| in_addr = (struct sockaddr_in *)searcher->ifa_addr; | |
| memcpy(ipaddr, &(in_addr->sin_addr), sizeof(struct in_addr)); | |
| ret = 0; | |
| break; | |
| } | |
| searcher = searcher->ifa_next; | |
| } | |
| if(ret != 0) { | |
| ret = -1; | |
| } | |
| freeifaddrs(ifap); | |
| return ret; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment