BBS水木清华站∶精华区

发信人: hellguard (小四), 信区: Unix        
标  题: Re: 如何在程序中获取本机的IP? (转载) 
发信站: BBS 水木清华站 (Thu Aug 17 12:24:31 2000) 
 
【 在 frisky (小六子) 的大作中提到: 】 
 【 以下文字转载自 Linux 讨论区 】 
 【 原文由 frisky 所发表 】 
 在linux下,redhat 6.2 
 我需要在程序中获取本机的IP,我的机器有两块网卡,一块对内,一块对外,分别设置 
 为不同的IP。我现在地做法是: 
 首先gethostname(hostname,sizeof(hostname)) 
 然后gethostbyname(hostname) 
 但返回的为空,我用netconfig把两块网卡的名字都改成一个,这样只是获得了一个 
 地址,即h_addr_list[1]为空。 
 不知道我这样做是否有问题,或者有其他的方法。或者系统的设置部分还需调整, 
 烦请告知,3x. 
 ................... 
如果是两块网卡,就另外指定设备名即可。 
 
#include <stdio.h> 
#include <string.h> 
#include <netdb.h> 
#include <arpa/inet.h> 
#include <netinet/in.h> 
#include <sys/types.h> 
#include <sys/socket.h> 
#include <sys/ioctl.h> 
#include <net/if.h> 
#include <net/if_arp.h> 
#include <net/ethernet.h> 
#include <signal.h> 
#include <netinet/ip.h> 
 
struct  in_addr myself, mymask; 
 
int     fd_arp;                 /* socket fd for receive packets */ 
struct  ifreq   ifr;            /* ifr structure */ 
 
main (int argc, char* argv[]) { 
    char                device[32];  /* ethernet device name */ 
    struct sockaddr     from, to; 
    int                 fromlen; 
    struct sockaddr_in *sin_ptr; 
    u_char             *ptr; 
    int                 n; 
 
    strcpy(device, "eth0"); 
 
    if ((fd_arp = socket(AF_INET, SOCK_PACKET, htons(0x0806))) < 0) { 
        perror( "arp socket error"); 
        exit(-1); 
    } 
 
    strcpy(ifr.ifr_name, device); 
    /* ifr.ifr_addr.sa_family = AF_INET; */ 
 
    /* get ip address of my interface */ 
    if (ioctl(fd_arp, SIOCGIFADDR, &ifr) < 0) { 
        perror("ioctl SIOCGIFADDR error"); 
        exit(-1); 
    } 
    sin_ptr = (struct sockaddr_in *)&ifr.ifr_addr; 
    myself  = sin_ptr->sin_addr; 
 
    /* get network mask of my interface */ 
    if (ioctl(fd_arp, SIOCGIFNETMASK, &ifr) < 0) { 
        perror("ioctl SIOCGIFNETMASK error"); 
        exit(-1); 
    } 
    sin_ptr = (struct sockaddr_in *)&ifr.ifr_addr; 
    mymask  = sin_ptr->sin_addr; 
 
    /* get mac address of the interface */ 
    if (ioctl(fd_arp, SIOCGIFHWADDR, &ifr) < 0) { 
        perror("ioctl SIOCGIFHWADDR error"); 
        exit(-1); 
    } 
    ptr = (u_char *)&ifr.ifr_ifru.ifru_hwaddr.sa_data[0]; 
    printf( "request mac %02x:%02x:%02x:%02x:%02x:%02x, ",  
            *ptr, *(ptr + 1), *(ptr + 2), *(ptr + 3),  
            *(ptr + 4), *(ptr + 5) ); 
    printf( "request netmask  %s ", inet_ntoa(mymask)); 
    printf( "request IP  %s\n", inet_ntoa(myself)); 
 
}  /* end of main */ 
-- 
 
            也许有一天,他再从海上蓬蓬的雨点中升起, 
            飞向西来,再形成一道江流,再冲倒两旁的石壁, 
            再来寻夹岸的桃花。然而,我不敢说来生,也不敢信来生...... 
 
 
※ 来源:·BBS 水木清华站 smth.org·[FROM: 159.226.41.166] 

BBS水木清华站∶精华区