linux 下读取eth0网卡的ip地址

gethostaddr
#include <stdio.h>
#include <net/if.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/ioctl.h>
#include <string.h>

int main(void)
{
    int                fd; 
    char               buf[100];
    struct ifreq       ifr;
    struct sockaddr_in *sa = NULL;

    fd = socket(AF_INET, SOCK_STREAM, 0); 
    strcpy(ifr.ifr_name, "eth0");
    if (ioctl(fd, SIOCGIFADDR, &ifr) < 0) {
        perror("ioctl");
    }   
    sa = (struct sockaddr_in *)(&ifr.ifr_addr);
    printf("ip: %s\n", inet_ntop(AF_INET, &sa->sin_addr, buf, sizeof (buf)));
    return 0;
}
posted @ 2012-11-08 18:17  追心  阅读(674)  评论(0编辑  收藏  举报