SW 개발

Unix,Linux / 네트웍프로그래밍 / 예제소스 / 자신의 ip 얻어오기..

. . . 2009. 4. 21. 01:19
반응형
  • 마크다운변환 : 20190905

  • 출처 : 나.
  • 기타사항 : 틀린사항은 댓글로 달아주세여~

예제코드

#include <netinet/ether.h> 
#include <net/ethernet.h> 
#include <string.h> 
#include <sys/types.h> 
#include <sys/socket.h> 
#include <sys/ioctl.h> 
#include <net/if.h> 
#include <netinet/in.h> 
#include <arpa/inet.h> 
#include <stdlib.h> 
#include <stdio.h> 

int main(int argc,char**argv) 
{ 
    int sockfd; 
    char ipstr[40]; 
    struct ifreq ifr; 

    if ( argc != 2 ) 
    { 
        printf("Usage %s\n",argv[0]); 
        return 0; 
    } 

    strncpy(ifr.ifr_name,argv[1],IFNAMSIZ); 
    sockfd =socket(AF_INET,SOCK_STREAM,0); 

    if (ioctl(sockfd,SIOCGIFADDR,&ifr)< 0 ) 
    { 
        perror("ioctl"); 
        return -1; 
    } 

    inet_ntop(AF_INET,ifr.ifr_addr.sa_data+2,ipstr,sizeof(struct sockaddr)); 

    printf("ip addr is%s\n",ipstr); 
    return 0; 
} 

실행결과..

:!./testip eth0 
ip addr is203.240.202.243
반응형