簡體   English   中英

在Windows中從接口名稱獲取IP地址

[英]To get IP Address from interface name in Windows

我想知道,winapi可以使用接口名稱從中獲取ipaddress。 其Linux版本如下。

#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/ioctl.h>
#include <netinet/in.h>
#include <net/if.h>
#include <unistd.h>
#include <arpa/inet.h>
int main()
{
    int fd;
    struct ifreq ifr;
    char iface[] = "eth0";
    fd = socket(AF_INET, SOCK_DGRAM, 0);
    //Type of address to retrieve - IPv4 IP address
    ifr.ifr_addr.sa_family = AF_INET;
    //Copy the interface name in the ifreq structure
    strncpy(ifr.ifr_name , iface , IFNAMSIZ-1);
    ioctl(fd, SIOCGIFADDR, &ifr);
    close(fd);
    //display result
    printf("%s - %s\n" , iface , inet_ntoa(( (struct sockaddr_in *)&ifr.ifr_addr )->sin_addr) );
    return 0;
}

我正在尋找類似的功能(如上述代碼),但適用於C ++中的Windows

請參見GetAdaptersAddresses函數的示例。 FriendlyName和FirstUnicastAddress是您需要的字段。

http://msdn.microsoft.com/zh-CN/library/windows/desktop/aa365915%28v=vs.85%29.aspx

另請參閱: 從IPv4地址獲取網絡接口名稱

SIGAR是用於獲取系統信息(CPU,RAM,DISK和網絡)的跨平台庫。 它將允許您列出Mac / Windows / Linux上的所有網絡接口,並獲取您可能需要的任何其他信息。

http://support.hyperic.com/display/SIGAR/首頁

如果您不想使用整個庫,我相信您可以檢查代碼以找到所需的片段。

也許您可以根據自己的需要進行調整...

http://kodeyard.blogspot.in/2009/09/get-ip-address-in-cwindows.html

您必須先初始化WinSock,然后才使用gethostname,gethostbyname和inet_ntoa函數。 以下鏈接將為您提供幫助。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM