2008년 9월 24일 수요일

linux 에서 특정 인터페이스 카드의 상태 읽어오기

MAC 어드레스 얻는것과 마찬가지로 걍 ioctl 쓰는건데.. 역시 샘플로 만들어둔 코드 그냥 지우기 뭐해서 적어둔다. 랜선이 껴진 상태인지 판단하기 위해서 만든 코드인데 현재 내 PC 네트웍을 죽일수가 없어서 아직 테스트는 안해봤다.

내일 출근하면 랜선 뺐다 껴보고, 인터페이스 올리고 내리고 등등 하면서 플래그값 변화를 체크해보자.



#include <sys/socket.h>
#include <sys/types.h>
#include <net/if.h>
#include <sys/ioctl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

static void show_ifr_flags(unsigned int flags);

int main()
{
/* 인터페이스 이름을 eth0 으로 고정했는데 시스템 내의
* 인터페이스들을 얻어오려면 SIOCGIFCONF 참고
*/
const char* ifname = "eth0";

struct ifreq ifr;
memset(&ifr, 0, sizeof(ifr));
strncpy(ifr.ifr_name, ifname, IFNAMSIZ);

int s = socket(PF_INET, SOCK_STREAM, 0);
if(s<0) perror("socket failed"); /* TODO 더 나은 에러처리 */
int r = ioctl(s, SIOCGIFFLAGS, &ifr);
if(r<0) perror("ioctl failed"); /* TODO 더 나은 에러처리 */

show_ifr_flags(ifr.ifr_flags);

close(s);
}

/* 내 시스템에서 net/if.h 를 보면 이 flag 의 타입으로 unsigned short 가
* 쓰였다. 환경마다 다를것 같기도 헌데..
*/
void show_ifr_flags(unsigned int flags)
{
#define SHOW_FLAG(flag, desc) printf("%-16s = %d // %s\n", #flag, (flags&flag)!=0, desc);
SHOW_FLAG(IFF_UP, "Interface is up");
SHOW_FLAG(IFF_BROADCAST, "Broadcast address valid");
SHOW_FLAG(IFF_DEBUG, "Turn on debugging");
SHOW_FLAG(IFF_LOOPBACK, "Is a loopback net");
SHOW_FLAG(IFF_POINTOPOINT, "Interface is point-to-point link");
SHOW_FLAG(IFF_NOTRAILERS, "Avoid use of trailers");
SHOW_FLAG(IFF_RUNNING, "Resources allocated");
SHOW_FLAG(IFF_NOARP, "No address resolution protocol");
SHOW_FLAG(IFF_PROMISC, "Receive all packets");
SHOW_FLAG(IFF_ALLMULTI, "Receive all multicast packets");
SHOW_FLAG(IFF_MASTER, "Master of a load balancer");
SHOW_FLAG(IFF_SLAVE, "Slave of a load balancer");
SHOW_FLAG(IFF_MULTICAST, "Supports multicast");
SHOW_FLAG(IFF_PORTSEL, "Can set media type");
SHOW_FLAG(IFF_AUTOMEDIA, "Auto media select active");
SHOW_FLAG(IFF_DYNAMIC, "Dialup device with changing addresses");
#undef SHOW_FLAG
}


음.. 돌려보고 결과를 적어둔다.

각 상황별 결과 보기


정리하자면
랜선끼고 ifup
IFF_UP = 1 // Interface is up
IFF_RUNNING = 1 // Resources allocated

랜선끼고 ifdown
IFF_UP = 0 // Interface is up
IFF_RUNNING = 0 // Resources allocated

랜선뽑고 ifup
IFF_UP = 1 // Interface is up
IFF_RUNNING = 0 // Resources allocated

랜선뽑고 ifdown
IFF_UP = 0 // Interface is up
IFF_RUNNING = 0 // Resources allocated


댓글 2개:

김태정 on Voiceportal :

trackback from: [linux/java]top 결과값 받아오기
리눅스 상에서 top를 실행하면 일정한 주기로 refresh된다. top을 실행한 후에 이를 다른 프로그램으로 보내주거나 파일로 저장하기 위해서 옵션을 넣어주면 된다. 먼저 man top를 해보자. 중요하게 봐두어야 할 것은 다음 두 옵션이다. -b : Batch mode operation Starts top in ’Batch mode’, which could be useful for sending output from top to other pro..

김태정 on Voiceportal :

trackback from: Red Hat Linux 5.2
아래 링크는 여러가지 리눅스를 다운 받을 수 있는 곳이다. 하지만 내가 찾는 5.2버전은 없는 것 같다... -0-;; http://letsopen.com/os/ 아래 링크는 레드햇 리눅스 5.2 버전의 설치 가이드 문서이다. 흠.. http://jamesthornton.com/redhat/linux/5.2/Installation-Guide-x86/ 5.0.0 설치 한글 문서 http://www.redhat.com/docs/manuals/enterp..