荔园在线

荔园之美,在春之萌芽,在夏之绽放,在秋之收获,在冬之沉淀

[回到开始] [上一篇][下一篇]


发信人: jjk (kernel), 信区: Linux
标  题: Re: Linux socket编程中用哪个函数获得本机IP(转寄)
发信站: 荔园晨风BBS站 (Sat Mar  2 22:39:52 2002), 转信

【 以下文字转载自 jjk 的信箱 】
【 原文由 jjksam@smth.org 所发表 】
发信人: hellguard (小四), 信区: Linux
标  题: Re: Linux socket编程中用哪个函数获得本机IP(转寄)
发信站: BBS 水木清华站 (Mon Feb  4 21:31:03 2002)

/*
 * display info about network interfaces
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <unistd.h>
#include <sys/socket.h>
#include <sys/ioctl.h>
#include <net/if.h>
#include <net/if_arp.h>
#include <arpa/inet.h>

#define inaddrr( x ) ( *( struct in_addr * )&ifr->x[ sizeof( sa.sin_port ) ] )
#define IFRSIZE      ( ( int )( size * sizeof( struct ifreq ) ) )

int main ( void )
{
    unsigned char *    u;
    int                sockfd, size = 1;
    struct ifreq *    ifr;
    struct ifconf      ifc;
    struct sockaddr_in sa;

    if ( 0 > ( sockfd = socket( AF_INET, SOCK_DGRAM, IPPROTO_IP ) ) )
    {
        fprintf( stderr, "Cannot open socket.\n" );
        exit( EXIT_FAILURE );
    }
    ifc.ifc_req = NULL;
    do
    {
        ++size;
        /* realloc buffer size until no overflow occurs  */
        if ( NULL == ( ifc.ifc_req = realloc( ifc.ifc_req, IFRSIZE ) ) )
        {
            fprintf( stderr, "Out of memory.\n" );
            exit( EXIT_FAILURE );
       }
        ifc.ifc_len = IFRSIZE;
        if ( ioctl( sockfd, SIOCGIFCONF, &ifc ) )
        {
            perror( "ioctl SIOCFIFCONF" );
            exit( EXIT_FAILURE );
        }
    } while ( IFRSIZE <= ifc.ifc_len );
    ifr = ifc.ifc_req;
    for ( ; ( char * )ifr < ( char * )ifc.ifc_req + ifc.ifc_len; ++ifr )
    {
        if ( ifr->ifr_addr.sa_data == ( ifr + 1 )->ifr_addr.sa_data )
        {
            continue;  /* duplicate, skip it */
        }
        if ( ioctl( sockfd, SIOCGIFFLAGS, ifr ) )
        {
            continue;  /* failed to get flags, skip it */
        }
        printf( "Interface:  %s\n", ifr->ifr_name );
        printf( "IP Address: %s\n", inet_ntoa( inaddrr( ifr_addr.sa_data ) ) );
        printf( "\n" );
    }  /* end of for */
    close( sockfd );
    return( EXIT_SUCCESS );
}  /* end of main */

【 在 hzqbbc (BBC·10年磨一剑) 的大作中提到: 】
: 好象网上有不少example哦。我砍过可惜忘记了。sigh~~


--

            也许有一天,他再从海上蓬蓬的雨点中升起,
            飞向西来,再形成一道江流,再冲倒两旁的石壁,
            再来寻夹岸的桃花。然而,我不敢说来生,也不敢信来生......


※ 来源:·BBS 水木清华站 smth.org·[FROM: 166.111.4.19]
--
※ 转载:·荔园晨风BBS站 bbs.szu.edu.cn·[FROM: 192.168.0.146]


[回到开始] [上一篇][下一篇]

荔园在线首页 友情链接:深圳大学 深大招生 荔园晨风BBS S-Term软件 网络书店