태터데스크 관리자

도움말
닫기
적용하기   첫페이지 만들기

태터데스크 메시지

저장하였습니다.

롸이언의 인생이야기 @ Innovate yourself ™


pancho <pan...@tee.com> wrote:
>Hello

>I would like to know if there is a way to know my ip address of each
>interface from a C program, if them are up or down...

>Of course, I can do it scanningf the output of "ifconfig", (more
>concretelly "ifconfig ppp0 | grep inetaddr"), but it would be great if
>exists the possibility of reading a structure with this information with a
>system call, just like sysinfo allows me to know how many free memory I
>have, for example.

>I have looked for such a function, but I havent found it. (I also have
>tried to look at the ifconfig code for a hint, but for me it is too
>complicated).

Below is a demo program that has been posted a few times previously.

/* display info about network interfaces */

#define _BSD_SOURCE

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <errno.h>
#include <sys/ioctl.h>
#include <sys/types.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)))

static int
get_addr(int sock, char * ifname, struct sockaddr * ifaddr) {

  struct ifreq *ifr;
  struct ifreq ifrr;
  struct sockaddr_in sa;

  ifr = &ifrr;
  ifrr.ifr_addr.sa_family = AF_INET;
  strncpy(ifrr.ifr_name, ifname, sizeof(ifrr.ifr_name));

  if (ioctl(sock, SIOCGIFADDR, ifr) < 0) {
    printf("No %s interface.\n", ifname);
    return -1;
  }

  *ifaddr = ifrr.ifr_addr;
  printf("Address for %s: %s\n", ifname, inet_ntoa(inaddrr(ifr_addr.sa_data)));
  return 0;

}

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_len = IFRSIZE;
  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);

  /* this is an alternate way to get info... */
  {
    struct sockaddr ifa;
    get_addr(sockfd, "ppp0", &ifa);
  }

  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)));

    /*
      This won't work on HP-UX 10.20 as there's no SIOCGIFHWADDR ioctl. You'll
      need to use DLPI or the NETSTAT ioctl on /dev/lan0, etc (and you'll need
      to be root to use the NETSTAT ioctl. Also this is deprecated and doesn't
      work on 11.00).

      On Digital Unix you can use the SIOCRPHYSADDR ioctl according to an old
      utility I have. Also on SGI I think you need to use a raw socket, e.g. s
      = socket(PF_RAW, SOCK_RAW, RAWPROTO_SNOOP)

      Dave

      From: David Peter <dave.pe...@eu.citrix.com>
     */

    if (0 == ioctl(sockfd, SIOCGIFHWADDR, ifr)) {

      /* Select which  hardware types to process.
       *
       *    See list in system include file included from
       *    /usr/include/net/if_arp.h  (For example, on
       *    Linux see file /usr/include/linux/if_arp.h to
       *    get the list.)
       */
      switch (ifr->ifr_hwaddr.sa_family) {
      default:
        printf("\n");
        continue;
      case  ARPHRD_NETROM:  case  ARPHRD_ETHER:  case  ARPHRD_PPP:
      case  ARPHRD_EETHER:  case  ARPHRD_IEEE802: break;
      }

      u = (unsigned char *) &ifr->ifr_addr.sa_data;

      if (u[0] + u[1] + u[2] + u[3] + u[4] + u[5]) {
        printf("HW Address: %2.2x.%2.2x.%2.2x.%2.2x.%2.2x.%2.2x\n",
             u[0], u[1], u[2], u[3], u[4], u[5]);
      }
    }

    if (0 == ioctl(sockfd, SIOCGIFNETMASK, ifr) &&
        strcmp("255.255.255.255", inet_ntoa(inaddrr(ifr_addr.sa_data)))) {
      printf("Netmask:    %s\n", inet_ntoa(inaddrr(ifr_addr.sa_data)));
    }

    if (ifr->ifr_flags & IFF_BROADCAST) {
      if (0 == ioctl(sockfd, SIOCGIFBRDADDR, ifr) &&
          strcmp("0.0.0.0", inet_ntoa(inaddrr(ifr_addr.sa_data)))) {
        printf("Broadcast:  %s\n", inet_ntoa(inaddrr(ifr_addr.sa_data)));
      }
    }

    if (0 == ioctl(sockfd, SIOCGIFMTU, ifr)) {
      printf("MTU:        %u\n",  ifr->ifr_mtu);
    }

    if (0 == ioctl(sockfd, SIOCGIFMETRIC, ifr)) {
      printf("Metric:     %u\n",  ifr->ifr_metric);
    }
    printf("\n");
  }

  close(sockfd);
  return EXIT_SUCCESS;

}
크리에이티브 커먼즈 라이선스
Creative Commons License
Posted by 롸이언
공부 이야기/컴퓨터 몽땅 l 2009/01/19 18:54

[원문]코쟁이 http://coders.tistory.com/search/timezone

Timezone on Linux

리눅스의 Timezone 및 DST는 TZ라는 환경변수에 의해 결정됩니다.

1. TZ 환경변수가 없을경우
TZ 환경변수가 없을경우는 시스템 타임존 디렉토리에 존재하는 특정파일을 읽어와 타임존과 DST정보를 설정하게 됩니다. 즉 /etc/localtime을 읽습니다. 이파일은 tzfile(5)형태로 지역의 타임존과 연도별 DST정보를 포함하고 있습니다.

2. TZ 환경변수가 있으나 빈값(Null)이거나 잘못된 형태로 기록되어 있을경우
이런경우는 UTC를 사용하게 됩니다. 흔히들 GMT라고 불리는데 GMT는 타임존의 이름이므로 정확한 표현은 UTC로 하세요.

3. TZ 환경변수가 있고 정확한 포맷으로 기록되어 있을경우
3.1. TZ 환경변수가 standard offset값만을 포함한 경우
우리나라가 여기에 해당됩니다. 즉 "타임존이 UTC에 비해 얼마 떨어졌는가"만을 표현하는 경우죠. 따라서 DST는 사용하고 있지 않은 지역이 됩니다.
TZ=STDhh[:mm]
STD: 키워드입니다. KST, GMT등이죠. 3글자 이상 알파벳만 허용됩니다. 단지 표시용 이므로 크게 상관 안하셔도 됩니다.
hh: 시간입니다.
mm: 분입니다. 옵션이므로 없어도 됩니다.

ex) Seoul : TZ=KST-9

3.2. TZ 환경변수가 dst 정보까지 포함한 경우
DST를 사용하는 지역이 여기에 해당됩니다. 타임존 정보뿐만 아니라 DST의 시작 일/시, 종료 일/시까지 포함하게 됩니다. 좀 복잡하니깐 차근차근 읽어주세요.
DST 시작/종료 일시 표현방식 : Mmonth.week.weekday/hour:min:sec
TZ=STDhh[:mm]DSTbias_hh:bias_mm,{DST 시작 일시},{DST 종료 일시}
STD,DST: 위와같이 키워드 입니다.
bias_hh, mm: DST시 변경될 시간, 분입니다.
month: 월, 1~12
week: 주, 1~5, 서수표현이며 몇번째 주를 나타냅니다.
weekday: 요일, 0-6, 0은 일요일, 6은 토요일 입니다.

ex) (GMT-05:00) Eastern Time (US & Canada) : TZ=STD5DST4:0,M4.1.0/2:0:0,M10.5.0/2:0:0

3.3. TZ 환경변수에 tzfile의 path가 포함된 경우
/etc/localtime 대신 다른 tzfile을 사용할경우에 사용됩니다.
TZ=:{TZFILEPATH}

ex) Seoul : TZ=:/usr/share/zoneinfo/ROK

위의 TZ환경변수를 이용하면 프로세스별로 독립적인 Timezone을 가지고 프로그래밍 할 수 있습니다. 참고로 windog에서는 안됩니다. 구현이 덜 된듯하더군요.
크리에이티브 커먼즈 라이선스
Creative Commons License

'공부 이야기 > 컴퓨터 몽땅' 카테고리의 다른 글

Awk 사용법  (0) 2008/08/06
Virtual IP setup  (0) 2008/08/04
Timezone on Linux  (2) 2008/07/21
NTPClient  (0) 2008/07/20
Lightbox JS  (0) 2008/06/18
epoll 서버 샘플 프로그래밍  (0) 2008/05/29
Posted by 롸이언
공부 이야기/컴퓨터 몽땅 l 2008/07/21 12:38

RAM 이 항상 부족한 Embedded System에서 물리적인 메모리를 더 추가하는 것은 여러가지로 문제점이 많다. 이때 좋은 방법이 메모리 Swap을 사용하는 것이다..

하드디스크가 부탁되거나 기타 외부 메모리가 있으면 더 많은 스왑을 잡을 수 있을것이다..

의외로 간단하게 아래와 같이 잡을수 있다.. 그러면 64M의 메모리가 하나 더 생긴다고 생각할 수 있다.


dd if=/dev/zero of=/swapfile bs=1024 count=65536

mkswap /swapfile

swapon /swapfile

 

 

부팅시 활성화 하려면 /etc/fstab 추가

/swapfile swap swap defaults 0 0

크리에이티브 커먼즈 라이선스
Creative Commons License
Posted by 롸이언
공부 이야기/컴퓨터 몽땅 l 2008/05/01 11:30

kelp.or.kr에서 holelee 님이 frame buffer 관해서 강의한 내용, DaVinci, 임베디드!
Frame buffer에 관해 많은 것을 알수 있는 자료입니다~~
감사합니다~

1. frame buffer 이야기(9) (임베디드강좌/이규명)
2. frame buffer 이야기(8) (임베디드강좌/이규명)
3. frame buffer 이야기(7) (임베디드강좌/이규명)
4. frame buffer 이야기(6) (임베디드강좌/이규명)
5. frame buffer 이야기(5) (임베디드강좌/이규명)
6. frame buffer 이야기(4) - 일반적인 mmap (임베디드강좌/이규명)
7. frame buffer 이야기(3) (임베디드강좌/이규명)
8. frame buffer 이야기(2) (임베디드강좌/이규명)
9. frame buffer 이야기(1) (임베디드강좌/이규명)

크리에이티브 커먼즈 라이선스
Creative Commons License

'공부 이야기 > 컴퓨터 몽땅' 카테고리의 다른 글

compiling openssh  (0) 2007/07/02
"비디오코덱 H.264로 통일하자"  (0) 2007/06/18
Frame Buffer 이야기 1~9  (0) 2007/05/25
GDB 매뉴얼~~  (0) 2007/04/27
OpenSSH에서 서버 키 생성 방법  (0) 2007/04/27
TPTP 프로파일링 Part 1  (0) 2007/04/27
Posted by 롸이언
공부 이야기/컴퓨터 몽땅 l 2007/05/25 15:33
1 

카테고리

꼭대기 (82)
롸이언 이야기 (7)
가족 이야기 (0)
친구 이야기 (1)
공부 이야기 (51)
취미 이야기 (17)
노래 이야기 (1)

달력

«   2010/03   »
  1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30 31      
Statistics Graph
tistory!get rss Tistory Tistory 가입하기! DNS Powered by DNSEver.com