// Obtain the local IP address Function
Qstring getlocalip () <br/>{</P> <p> int sock_get_ip; <br/> char ipaddr [50]; </P> <p> struct sockaddr_in * sin; <br/> struct ifreq ifr_ip; </P> <p> If (sock_get_ip = socket (af_inet, sock_stream, 0) =-1) <br/>{< br/> printf ("socket create failse... getlocalip! /N "); <br/> return" "; <br/>}</P> <p> memset (& ifr_ip, 0, sizeof (ifr_ip )); <br/> strncpy (ifr_ip.ifr_name, "eth0", sizeof (ifr_ip.ifr_name)-1); </P> <p> If (IOCTL (sock_get_ip, siocgifaddr, & ifr_ip) <0) <br/>{< br/> return ""; <br/>}< br/> sin = (struct sockaddr_in *) & ifr_ip.ifr_addr; <br/> strcpy (ipaddr, inet_ntoa (sin-> sin_addr); </P> <p> printf ("local IP: % s/n", ipaddr ); <br/> close (sock_get_ip); </P> <p> return qstring (ipaddr); <br/>}
// Function for modifying the IP address of the Local Machine
Int setlocalip (const char * ipaddr) <br/>{</P> <p> int sock_set_ip; </P> <p> struct sockaddr_in sin_set_ip; <br/> struct ifreq ifr_set_ip; </P> <p> bzero (& ifr_set_ip, sizeof (ifr_set_ip); </P> <p> If (ipaddr = NULL) <br/> return-1; </P> <p> If (sock_set_ip = socket (af_inet, sock_stream, 0) =-1 ); <br/>{< br/> perror ("socket create failse... setlocalip! /N "); <br/> return-1; <br/>}</P> <p> memset (& sin_set_ip, 0, sizeof (sin_set_ip )); <br/> strncpy (ifr_set_ip.ifr_name, "eth0", sizeof (ifr_set_ip.ifr_name)-1); </P> <p> sin_set_ip.sin_family = af_inet; <br/> sin_set_ip.sin_addr.s_addr = inet_addr (ipaddr); <br/> memcpy (& ifr_set_ip.ifr_addr, & sin_set_ip, sizeof (sin_set_ip )); </P> <p> If (IOCTL (sock_set_ip, siocsifaddr, & ifr_set_ip) <0) <br/>{< br/> perror ("not setup interface/N"); <br/> return-1; <br/>}</P> <p> // set the activation flag <br/> ifr_set_ip.ifr_flags | = iff_up | iff_running; </P> <p> // get the status of the device <br/> If (IOCTL (sock_set_ip, siocsifflags, & ifr_set_ip) <0) <br/>{< br/> perror ("siocsifflags"); <br/> return-1; <br/>}</P> <p> close (sock_set_ip); <br/> return 0; <br/>}
This article from the csdn blog, reproduced please indicate the source: http://blog.csdn.net/davidge333/archive/2010/01/24/5250566.aspx