Linux API/network2009. 8. 18. 14:51
vi /usr/include/linux/in.h

53 /* Internet address. */
54 struct in_addr {
55         __u32   s_addr;
56 };

char *inet_ntoa(struct in_addr in);

에서 사용하는 구조체이다.
단일 변수 하나의 구조체인데..
굳이 구조체로 만든 이유는.. IPv6 등을 위한걸려나..



사족 : 귀찮으면 int형으로 그냥 쓰면된다. 그런데.. 이 내용 저번에 적었던거 같은데... 기억이 안나네 -ㅁ-?
Posted by 구차니
Linux API/network2009. 8. 18. 11:16
이 녀석들은 데비안 출신이었나?

5.3.5. The network interface with the static IP

The network interface served by the static IP is configured by creating the configuration entry in the "/etc/network/interfaces" file as the following.

allow-hotplug eth0
iface eth0 inet static
address 192.168.11.100
netmask 255.255.255.0
broadcast 192.168.11.255
gateway 192.168.11.1
dns-domain lan
dns-nameservers 192.168.11.1

When the Linux kernel detects the physical interface eth0, the allow-hotplug stanza will cause ifup to bring up the interface and the iface stanza will cause ifup to use the static IP to configure the interface.


[링크 : http://www.debian.org/doc/manuals/debian-reference/ch05.en.html#_the_network_interface_with_the_static_ip]


간단하게 해석하자면, 물리적으로 연결이 되었음을 탐지하게 되면, 자동으로 설정을 실행한다는 의미이다.
(interface-eth0-를 up 시키고 iface구절을 실행함)


Check to see if a Network Link/Interface is up|down

ip link show eth0
//the iproute package is required. If there is no ip package, apt-get install iproute

If eth0 has a Network link, the following will be returned:
2: eth0: <BROADCAST,MULTICAST,UP> mtu 1500 qdisc pfifo_fast qlen 1000
link/ether 00:0c:29:26:57:4e brd ff:ff:ff:ff:ff:ff

If eth0 has no Network link, the following will be returned:
2: eth0: <BROADCAST,MULTICAST> mtu 1500 qdisc pfifo_fast qlen 1000
link/ether 00:0c:29:26:57:4e brd ff:ff:ff:ff:ff:ff

The "UP" is the operative word.


[링크 : http://wiki.kartbuilding.net/index.php/Ifup-ifdown]


실제로 ifup, ifdown 시에 제대로 interface가 up / down 되었는지 확인하는 방법이다.
Posted by 구차니
Linux API/network2009. 7. 30. 15:48
랜선을 뽑고 꼽으면 아래와 같은 메시지가 출력된다.

eth0 : link down
eth0 : link up

dmesg로 매번 감시할수도 없는 노릇이고 그래서 코드로 하는 법을 찾아 왔는데
아직까지는 컴파일도 못시켜 봤다..(써글넘의 타입)

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <signal.h>
#include <errno.h>
#include <sys/socket.h>
#include <sys/ioctl.h>
#include <stdint.h>
#include <net/if.h>
#include <netinet/in.h>
#include <ctype.h>

typedef uint32_t u32;
typedef uint16_t u16;
typedef uint8_t u8;

#include <linux/sockios.h>
#include <linux/ethtool.h>

// -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= //
// Get the link status. This returns TRUE if the link is up and FALSE
// otherwise.
//
int32_t link_stat()
{
        int s;
        struct ifreq ifr;
        struct ethtool_value eth;

        if((s = socket(AF_INET, SOCK_DGRAM, IPPROTO_IP)) == FAIL)
                ERRORS(Socket);

        bzero(&ifr, sizeof(ifr));
        strcpy(ifr.ifr_name, Eth0);
        ifr.ifr_data = (caddr_t) &eth;
        eth.cmd = ETHTOOL_GLINK;

        if(ioctl(s, SIOCETHTOOL, &ifr) == FAIL)
                ERRORS(Ioctl);
        (void)close(s);

        return (eth.data) ? TRUE:FALSE;
}

void main()
{
        int ret;
        ret = link_stat();

        if(ret == TRUE) printf("link up\n");
        else printF("link down\n");
}

[링크 : http://lkml.indiana.edu/hypermail/linux/kernel/0505.2/0754.html]

'Linux API > network' 카테고리의 다른 글

struct in_addr  (0) 2009.08.18
ifup/ifdown  (0) 2009.08.18
리눅스 소켓 프로그래밍 - linux socket programming  (0) 2009.07.17
fstat - 파일의 상태 얻어오기  (2) 2009.07.02
Linux File Descriptor / File pointer  (0) 2009.06.30
Posted by 구차니
Linux API/network2009. 7. 17. 15:04

내용



[링크 : http://wiki.kldp.org/Translations/html/Socket_Programming-KLDP/Socket_Programming-KLDP.html]
[링크 : http://www.lug.or.kr/docs/LINUX/others/97-11-5.htm]

'Linux API > network' 카테고리의 다른 글

ifup/ifdown  (0) 2009.08.18
[확인중] 이더넷 링크 상태 확인하기 - howto get link status  (0) 2009.07.30
fstat - 파일의 상태 얻어오기  (2) 2009.07.02
Linux File Descriptor / File pointer  (0) 2009.06.30
getline()  (0) 2009.06.25
Posted by 구차니
Linux API/network2009. 7. 2. 16:38
원래는 파일의 생성일을 알아보려고 찾았는데..
리눅스에서는 파일 생성일은 저장을 안한다고 한다.

	struct stat
	{
		dev_t     st_dev;     /* ID of device containing file */
		ino_t     st_ino;     /* inode number */
		mode_t    st_mode;    /* protection */
		nlink_t   st_nlink;   /* number of hard links */
		uid_t     st_uid;     /* user ID of owner */
		gid_t     st_gid;     /* group ID of owner */
		dev_t     st_rdev;    /* device ID (if special file) */
		off_t     st_size;    /* total size, in bytes */
		blksize_t st_blksize; /* blocksize for filesystem I/O */
		blkcnt_t  st_blocks;  /* number of blocks allocated */
		time_t    st_atime;   /* time of last access */
		time_t    st_mtime;   /* time of last modification */
		time_t    st_ctime;   /* time of last status change */
	};

위는 man fstat의 내용으로, 위에 보듯, time_t 구조체가 세개가 있는데
last access / modification / change 세가지 뿐이다.

[링크 : http://www.linuxhomenetworking.com/forums/showthread.php?t=17449]
Posted by 구차니
Linux API/network2009. 6. 30. 17:21
File Descriptor
int open(const char *pathname, int flags);
int open(const char *pathname, int flags, mode_t mode);
ssize_t read(int fildes, void *buf, size_t nbyte);
ssize_t write(int fildes, const void *buf, size_t nbyte);
int close(int fd);

int pipe(int filedes[2]); // filedes[0] is for reading, filedes[1] is for writing

int dup(int oldfd);
int dup2(int oldfd, int newfd);

ssize_t pread(int fildes, void *buf, size_t nbyte, off_t offset);
ssize_t pwrite(int fildes, const void *buf, size_t nbyte,off_t offset);

File Pointer
FILE *fopen(const char *path, const char *mode);
size_t fread(void *ptr, size_t size, size_t nmemb, FILE *stream);
size_t fwrite(const void *ptr, size_t size, size_t nmemb, FILE *stream);
int fclose(FILE *fp);

FILE *fdopen(int fildes, const char *mode);
FILE *freopen(const char *path, const char *mode, FILE *stream);

int fseek(FILE *stream, long offset, int whence);
long ftell(FILE *stream);
void rewind(FILE *stream);
int fgetpos(FILE *stream, fpos_t *pos);
int fsetpos(FILE *stream, fpos_t *pos);

FILE *popen(const char *command, const char *type);
int pclose(FILE *stream);

'Linux API > network' 카테고리의 다른 글

리눅스 소켓 프로그래밍 - linux socket programming  (0) 2009.07.17
fstat - 파일의 상태 얻어오기  (2) 2009.07.02
getline()  (0) 2009.06.25
fork에 관한 짧은 이야기  (2) 2009.06.23
signal / kill / raise  (0) 2009.06.21
Posted by 구차니
Linux API/network2009. 6. 25. 19:40
말그대로 라인을 얻어오는 함수이다.

SYNOPSIS
       #define _GNU_SOURCE
       #include <stdio.h>

       ssize_t getline(char **lineptr, size_t *n, FILE *stream);
       ssize_t getdelim(char **lineptr, size_t *n, int delim, FILE *stream);

DESCRIPTION
       getline()  reads an entire line from stream, storing the address of the buffer containing the text into *lineptr.
       The buffer is null-terminated and includes the newline character, if one was found.

       If *lineptr is NULL, then getline() will allocate a buffer for storing the line, which should  be  freed  by  the
       user  program.   Alternatively,  before calling getline(), *lineptr can contain a pointer to a malloc()-allocated
       buffer *n bytes in size. If the buffer is not large enough to hold the line, getline() resizes it with realloc(),
       updating  *lineptr  and *n as necessary. In either case, on a successful call, *lineptr and *n will be updated to
       reflect the buffer address and allocated size respectively.

       getdelim() works like getline(), except a line delimiter other than newline can be  specified  as  the  delimiter
       argument. As with getline(), a delimiter character is not added if one was not present in the input before end of
       file was reached.

함수형을 보면, 파일에서 한줄씩(그러니까 CR/LF 까지) 읽어 오는데,
주의해야 할 점은, getline() 함수 내부적으로 malloc()를 호출 한다는 것이다.
즉, 만약에 malloc()을 해주지 않으려면, NULL 값인 포인터를 넘겨주면
알아서 malloc() 하거나 realloc() 해주므로 많은 신경을 쓰지 않아도 된다.

단, 마지막 getline() 호출 후, 사용이 끝나면 반드시 free()를 해주어야 한다.

[링크 : http://linux.die.net/man/3/getline]
Posted by 구차니
Linux API/network2009. 6. 23. 00:50
fork()는 리눅스 시스템 콜로서, 프로세스를 생성한다.

#include "stdio.h"
#include "unistd.h"

int main() { pid_t pid; pid = fork();
switch( pid) { case -1: // fail case 0: // child default: // parent break; } }
개략적인 코드는 위와 같은데,
왜! switch 문데 child와 parent가 동시에 들어가는지에 대해서 생각을 해보도록 하자.

일단 fork() + exec() 의 조합으로 쓰게 되는데,
fork()는 프로세스를 생성하고, exec()는 프로그램을 바꾸어서 실행하는 역활을 한다.
다시 앞을 자세히 보자.

프로세스를 생성한다.

어려운 이야기를 제외하고, 프로세스는 메모리상에 올라와있는(적재되어 있는, 혹은 메모리에 load된)
프로그램으로, 프로세스를 생성하는 가장 편한 방법은 복사이다.
현재 수행중인 프로세스의 내용을 그대로 복사해서 다른 pid를 준다.
그게 바로 fork 이고, 위의 switch문을 이해할 수 있는 키가 된다.

굳이 비유를 하자면, 예전에 일요일에 했던 이휘재가 그래 결정했어! 를 외치던 그 프로그램을 떠올려 보자.
어느 시점에서 그대로 복제한 메모리의 정보가 생성이 되었고
그 분기점에서 어느길을 택할지를 결정하여 주면, 각각의 프로그램이 따로 돌아가게 된다.


즉, 복사한 시점에서 표지판 역활을 해주는 것이
fork()의 리턴값인 pid_t 형의 pid 이고,
이 값이 어느 쪽으로 분기되어 갈지를 결정하게 해주는 것이다.

그런 이유로, Parent, Child 의 코드가 하나의 소스에 들어 있게 되고
별거 아닌 것 같지만, 상당히 헷갈리는(왜 코드가 하나에 들어 있지?) 이유가 된다.

[링크 : http://linux.die.net/man/2/fork]

'Linux API > network' 카테고리의 다른 글

Linux File Descriptor / File pointer  (0) 2009.06.30
getline()  (0) 2009.06.25
signal / kill / raise  (0) 2009.06.21
flock - apply or remove an advisory lock on an open file  (0) 2009.06.20
네트워크 장치 갯수 얻기 (get amount of eth?)  (0) 2009.06.18
Posted by 구차니
Linux API/network2009. 6. 21. 13:04
signal - ANSI C signal handling
kill - send signal to a process
raise - send a signal to the current process

signal()은 시그널 핸들러를 등록하고
 #include <signal.h>
 sighandler_t signal(int signum, sighandler_t handler);

kill은 시그널 을 전송하고
 #include <sys/types.h>
 #include <signal.h>
 int kill(pid_t pid, int sig);

raise는 자기자신에게 시그널을 전송한다.
 #include <signal.h>
 int raise(int sig);
 kill(getpid(), sig);

아무래도, pid 단위로 시그널을 전송함으로서 제어에 상당한 제약이 있을것으로 보인다.
그리고 쓰레드는 2.5 커널 이상 부터는 pid가 동일하게 나온다고 한다.
[링크 : http://kldp.org/node/35609]

*** man page ***
[signal(2) : http://linux.die.net/man/2/signal]
[kill(2) : http://linux.die.net/man/2/kill]
[raise(2) : http://linux.die.net/man/3/raise]

*** joinc wiki ***
시그널 처리하기
시그널 사용하기 1
시그널 사용하기 2
리눅스 시스템 프로그래밍 6장 시그널

'Linux API > network' 카테고리의 다른 글

getline()  (0) 2009.06.25
fork에 관한 짧은 이야기  (2) 2009.06.23
flock - apply or remove an advisory lock on an open file  (0) 2009.06.20
네트워크 장치 갯수 얻기 (get amount of eth?)  (0) 2009.06.18
gateway 정보  (0) 2009.06.05
Posted by 구차니
Linux API/network2009. 6. 20. 18:55
flock은 이름대로 파일 디스크립터를 lock 하거나 unlock 하는데 사용한다.
멀티 유저/ 멀티 프로세스 OS인 관계로 Linux/Unix에서는 열린 파일도 여러사람이 또 열어서 쓸 수 있는데
다르게 말하자면 시리얼 포트 역시 동시에 여러사람이 열어서 사용이 가능하다는 의미이다.

하지만, 시리얼 포트를 동시에 여러 사람이 열어서 사용하다 보면 문제가 발생할 수도 있기에
(내용이 서로 엇갈린다던가) 특정 시기에 대해서는 타인이 사용하지 못하도록 배타적으로 잠궈야 할 때도 있다.

int flock(int fd, int operation);

    LOCK_SH
        Place a shared lock. More than one process may hold a shared lock for a given file at a given time.

    LOCK_EX
        Place an exclusive lock. Only one process may hold an exclusive lock for a given file at a given time.

    LOCK_UN
        Remove an existing lock held by this process.

[링크 : http://linux.die.net/man/2/flock]

LOCK_EX로 하면 자기만 쓸 수 있도록 잠그는 것이고,
LOCK_UN으로 잠금을 해제 한다.



[링크 : http://feedtome.springnote.com/pages/141729]
[링크 : http://stackoverflow.com/questions/691676/getting-exclusive-access-to-a-tty-device-from-a-root-program-on-linux]

'Linux API > network' 카테고리의 다른 글

fork에 관한 짧은 이야기  (2) 2009.06.23
signal / kill / raise  (0) 2009.06.21
네트워크 장치 갯수 얻기 (get amount of eth?)  (0) 2009.06.18
gateway 정보  (0) 2009.06.05
linux에서 ip/mac address 받아오기 관련 링크  (0) 2009.06.05
Posted by 구차니