linux c获取IP地址

2015-07-14 0 409
linux c获取IP地址
#include <stdio.h>
#include <sys/socket.h>
#include <sys/ioctl.h>
#include <netinet/in.h>
#include <net/if.h>
#include <string.h>
#include <arpa/inet.h>

int main(int argc, char **argv)
{
    int sockfd;
    struct ifreq ifr;

    char *ifname="eth0";
    strncpy(ifr.ifr_name, ifname, IFNAMSIZ-1);

    sockfd = socket(AF_INET, SOCK_STREAM, 0);
    if(ioctl(sockfd, SIOCGIFADDR, &ifr) == -1)
    {
        printf("Error\n");
        return;
    }

    struct sockaddr_in *myaddr;
    myaddr = (struct sockaddr_in*)&(ifr.ifr_addr);
    printf("IP: %s\n", inet_ntoa(myaddr->sin_addr));
}

遇见资源网 c/c++ linux c获取IP地址 http://www.ox520.com/10257.html

常见问题

相关文章

发表评论
暂无评论
官方客服团队

为您解决烦忧 - 24小时在线 专业服务