在Linux下擷取IP地址

來源:互聯網
上載者:User
在Linux下擷取IP地址,用Shell可以實現,用代碼當然也可以,我今天要探討的便是在C語言中擷取本機IP地址。

經過我的驗證,網路上很常見的實用 gethostname(), gethostbyname() 以及 uname()的方法並行不通,這點在uname的man page上也可見一斑。

這裡我們實用的方法是首先擷取socket,然後通過調用ioctl擷取其IP地址的方法。
主要的代碼塊和標頭檔如下所示。#include <sys/socket.h>
#include <sys/ioctl.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <net/if.h>

int sock_fd;
struct  my_addr;
struct ifreq ifr;
    unsigned char * addr;

#define ETH_INTERFACE_NAME    "eth0"

    /**//* Get socket file descriptor */
    if ((sock_fd = socket(PF_INET, SOCK_DGRAM, 0)) == -1)...{
        perror("socket");
        exit(1);
    }

    /**//* Get IP Address */
    strncpy(ifr.ifr_name, ETH_INTERFACE_NAME, IF_NAMESIZE);
    ifr.ifr_name[IFNAMSIZ-1]='/0';

    if (ioctl(sock_fd, SIOCGIFADDR, &ifr) < 0)...{
        perror("ioctl");
        exit(1);
    }

    memcpy(&my_addr, &ifr.ifr_addr, sizeof(my_addr));
    addr=inet_ntoa(my_addr.sin_addr);

得到了addr之後,想怎麼處理就看你了。
另外:這裡如果實用 inet_ntop()函數代替inet_ntoa的話可以獲得對IPV6更好的支援。 

 關於struct ifreq,請參考
http://linux.about.com/library/cmd/blcmdl7_netdevice.htm

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.