# Include <stdio. h>
# Include <stdlib. h>
# Include <error. h>
# Include <string. h>
# Include <netdb. h>
# Include <sys/types. h>
# Include <netinet/in. h>
# Include <sys/socket. h>
# Include <unistd. h>
# Include <sys/IOCTL. h>
# Include <ARPA/inet. h>
# Include <net/if_arp.h>
# Include <net/If. h>
# Include <ARPA/inet. h>
# Include "string"
Using namespace STD;
Int getlocaip (const char * Eth, unsigned & IP)
{
Int sockfd;
If (-1 = (sockfd = socket (pf_inet, sock_stream, 0 )))
{
Perror ("socket ");
Return-1;
}
Struct ifreq req;
Bzero (& req, sizeof (struct ifreq ));
Strcpy (req. ifr_name, ETH );
If (IOCTL (sockfd, siocgifaddr, & req) <0)
{
Fprintf (stderr, "IOCTL failed. \ n ");
Return-1;
}
Struct sockaddr_in * Host;
Host = (struct sockaddr_in *) & Req. ifr_addr;
IP = (unsigned) Host-> sin_addr.s_addr;
Close (sockfd );
Return 0;
}
Int main (INT argc, char ** argv)
{
Unsigned IP address;
String str_ip = "eth0 ";
Unsigned ret = getlocaip (str_ip.c_str (), ip );
If (ret = 0)
{
Char c_ip [16];
Memset (c_ip, 0, 16 );
Inet_ntop (af_inet, & IP, c_ip, 16 );
Printf ("loca_ip: % s \ n", c_ip );
}
Return 0;
}
Original
Http://blog.chinaunix.net/uid-26707720-id-3297624.html
Http://wenku.baidu.com/view/59f4508d680203d8ce2f2412.html ###