获得网络接口为eth0的IP地址
#include
#include
#include
#include
#include
#include
#include
#include
#include
#define MAXINTERFACES 16
#define MAC_ADDR_LEN 18
#define ADDR_LEN 16
#define ETH_INTERFACE_NAME "eth0"
void err_quit(char *msg);
char *getIP(char *addr);
int main(int argc, char *argv[])
{
char addr[ADDR_LEN];
getIP(addr);
return 0;
}
void err_quit(char *msg)
{
perror(msg);
exit(1);
}
char *getIP(char *addr)
{
int sock_fd;
struct ifreq ifr;
if((sock_fd = socket(AF_INET, SOCK_DGRAM, 0)) < 0)
err_quit("Create socket failed");
strncpy(ifr.ifr_name, ETH_INTERFACE_NAME, IF_NAMESIZE);
ifr.ifr_name[IF_NAMESIZE - 1] = '\0';
if(ioctl(sock_fd, SIOCGIFADDR, &ifr) < 0)
err_quit("Get interface address failed");
addr = inet_ntoa(((struct sockaddr_in*)(&ifr.ifr_addr))->sin_addr);
printf("IP address is %s\n", addr);
return addr;
}