How to get the IP address on the local host? I found a simply way. No using the system call gethostbyname(), using iocl(), it get an IP address directly from the ether card or call a ether inface.
The following code is the function.
#include <netdb.h>
#include <sys/socket.h>
#include <sys/ioctl.h>
#include <net/if.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <stdlib.h>
#include <stdio.h>
/*
* Fuction: getLocalIP();
* Description: get the ip of the localhost.
* Param: None
* Return: unsigned long // ip address; return 0 if fail.
*/
unsigned long getSelfIP() {
unsigned long lIP = 0L;
int inet_sock = -1;
struct ifreq ifr;
inet_sock = socket(AF_INET, SOCK_STREAM, 0);
// eth0 interface
strcpy(ifr.ifr_name, "eth0");
// get address
if (ioctl(inet_sock, SIOCGIFADDR, &ifr) == 0) {
lIP = ((struct sockaddr_in*)&(ifr.ifr_addr))->sin_addr.s_addr;
//unsigned char *ip = (unsigned char*)&lIP;
//fprintf(stderr, ">> [%u.%u.%u.%u]/n", ip[0], ip[1], ip[2], ip[3]);
}
return lIP;
}