2014년 11월 6일 목요일

miniterm.c

/******************************************************************************
 * miniterm.c
 * 
 * Adapted from the example program distributed with the Linux Programmer's
 * Guide (LPG). This has been robustified and tweaked to work as a debugging 
 * terminal for Xen-based machines.
 * 
 * Modifications are released under GPL and copyright (c) 2003, K A Fraser
 * The original copyright message and license is fully intact below.
 */

/*
 *  AUTHOR: Sven Goldt (goldt@math.tu-berlin.de)
 *
 *  This program is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU General Public License
 *  as published by the Free Software Foundation; either version 2
 *  of the License, or (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 */

#include <termios.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <signal.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <string.h>

#define DEFAULT_BAUDRATE   115200
#define DEFAULT_SERDEVICE  "/dev/ttyS0"
#define ENDMINITERM        0x1d

volatile int stop = 0;

void child_handler(int s)
{
    stop = 1;
}

int cook_baud(int baud)
{
    int cooked_baud = 0;
    switch ( baud )
    {
    case     50: cooked_baud =     B50; break;
    case     75: cooked_baud =     B75; break;
    case    110: cooked_baud =    B110; break;
    case    134: cooked_baud =    B134; break;
    case    150: cooked_baud =    B150; break;
    case    200: cooked_baud =    B200; break;
    case    300: cooked_baud =    B300; break;
    case    600: cooked_baud =    B600; break;
    case   1200: cooked_baud =   B1200; break;
    case   1800: cooked_baud =   B1800; break;
    case   2400: cooked_baud =   B2400; break;
    case   4800: cooked_baud =   B4800; break;
    case   9600: cooked_baud =   B9600; break;
    case  19200: cooked_baud =  B19200; break;
    case  38400: cooked_baud =  B38400; break;
    case  57600: cooked_baud =  B57600; break;
    case 115200: cooked_baud = B115200; break;
    }
    return cooked_baud;
}

int main(int argc, char **argv)
{
    int              fd, c, cooked_baud = cook_baud(DEFAULT_BAUDRATE);
    char            *sername = DEFAULT_SERDEVICE;
    struct termios   oldsertio, newsertio, oldstdtio, newstdtio;
    struct sigaction sa;
    static char start_str[] = 
        "************ REMOTE CONSOLE: CTRL-] TO QUIT ********\r\n";
    static char end_str[] =
        "\n************ REMOTE CONSOLE EXITED *****************\n";

    while ( --argc != 0 )
    {
        char *p = argv[argc];
        if ( *p++ != '-' )
            goto usage;
        if ( *p == 'b' )
        {
            p++;
            if ( (cooked_baud = cook_baud(atoi(p))) == 0 )
            {
                fprintf(stderr, "Bad baud rate '%d'\n", atoi(p));
                goto usage;
            }
        }
        else if ( *p == 'd' )
        {
            sername = ++p;
            if ( *sername == '\0' )
                goto usage;
        }
        else
            goto usage;
    }

    /* Not a controlling tty: CTRL-C shouldn't kill us. */
    fd = open(sername, O_RDWR | O_NOCTTY);
    if ( fd < 0 )
    {
        perror(sername); 
        exit(-1);
    }
 
    tcgetattr(fd, &oldsertio); /* save current modem settings */
 
    /*
     * 8 data, no parity, 1 stop bit. Ignore modem control lines. Enable 
     * receive. Set appropriate baud rate. NO HARDWARE FLOW CONTROL!
     */
    newsertio.c_cflag = cooked_baud | CS8 | CLOCAL | CREAD;

    /* Raw input. Ignore errors and breaks. */
    newsertio.c_iflag = IGNBRK | IGNPAR;

    /* Raw output. */
    newsertio.c_oflag = OPOST;

    /* No echo and no signals. */
    newsertio.c_lflag = 0;
 
    /* blocking read until 1 char arrives */
    newsertio.c_cc[VMIN]=1;
    newsertio.c_cc[VTIME]=0;
 
    /* now clean the modem line and activate the settings for modem */
    tcflush(fd, TCIFLUSH);
    tcsetattr(fd,TCSANOW,&newsertio);
 
    /* next stop echo and buffering for stdin */
    tcgetattr(0,&oldstdtio);
    tcgetattr(0,&newstdtio); /* get working stdtio */
    newstdtio.c_iflag &= ~(BRKINT | ICRNL | INPCK | ISTRIP | IXON);
    newstdtio.c_oflag &= ~OPOST;
    newstdtio.c_cflag &= ~(CSIZE | PARENB);
    newstdtio.c_cflag |= CS8;
    newstdtio.c_lflag &= ~(ECHO | ICANON | IEXTEN | ISIG);
    newstdtio.c_cc[VMIN]=1;
    newstdtio.c_cc[VTIME]=0;
    tcsetattr(0,TCSANOW,&newstdtio);

    /* Terminal settings done: now enter the main I/O loops. */
    switch ( fork() )
    {
    case 0:
        close(1); /* stdout not needed */
        for ( c = (char)getchar(); c != ENDMINITERM; c = (char)getchar() )
            write(fd,&c,1);
        tcsetattr(fd,TCSANOW,&oldsertio);
        tcsetattr(0,TCSANOW,&oldstdtio);
        close(fd);
        exit(0); /* will send a SIGCHLD to the parent */
        break;
    case -1:
        perror("fork");
        tcsetattr(fd,TCSANOW,&oldsertio);
        close(fd);
        exit(-1);
    default:
        write(1, start_str, strlen(start_str));
        close(0); /* stdin not needed */
        sa.sa_handler = child_handler;
        sa.sa_flags = 0;
        sigaction(SIGCHLD,&sa,NULL); /* handle dying child */
        while ( !stop )
        {
            read(fd,&c,1); /* modem */
            c = (char)c;
            write(1,&c,1); /* stdout */
        }
        wait(NULL); /* wait for child to die or it will become a zombie */
        write(1, end_str, strlen(end_str));
        break;
    }

    return 0;

 usage:
    printf("miniterm [-b<baudrate>] [-d<devicename>]\n");
    printf("Default baud rate: %d\n", DEFAULT_BAUDRATE);
    printf("Default device: %s\n", DEFAULT_SERDEVICE);
    return 1;
}

2014년 8월 25일 월요일

Openwrt -2기 ?


OpenWrt에 대해서 처음 접했을때는 회의시간이었다. 앞으로의 사업의 한축으로 다른회사들도 준비를 하고있다는 이야기였다. 처음 접했을때에 나를 대단히 힘들게 만들던것이었지만,
한편으로 그들의 시도가 재미있게 느껴졌다.

그뒤로 대략 5개월정도 흘렀다. 이제 대략, 감이 잡힌다. 한가지 특징적인것은 Openwrt는 상당히 유연하게 각각의 제품들에게 유연하게 대처가 가능하게 SDK가 설계되었다는점이다.

이것은 대단히 놀라운 시도라고 생각한다. 보통은 펨웨어를 제작할때에 몇개의 제품들을 지원하는 경우가 있지만, 새롭게 추가도 가능하게 만드는일은 드물기 때문이다.

국내에도 상당히 사용중인것으로 알고있지만, 아직 자료는 많지 않다. 사실은 책도 나왔지만, 교수님이 학생들에게 맞게 작성된것이기때문에 내수준에서는 음....

사실은 그다지 특별하게 추가될 내용도 없는것같지만, 언제 한번 정리를 해봤으면 한다.

2014년 7월 26일 토요일

[rapsberry pi] make Acesse Point

I finally succeeded in building a router with a raspberry pi.  I am embedded network engineer. and It have been taken a long time,ridiculous. However, I'm satisfied.
0.subject


The using raspberry pie, the goal is to implement a wireless router.




1.Devices





  • raspberry pi
  • RTL8185(LAN-STAR LS-NAL11)
  • RTL8188CU(Wevo U150 - ) 
  • MAX232



you can see device list. USB-wire LAN card is used for LAN, wifi-USB is used to the product with 8188CU.

When the network is initialized MAX232 ssh connection is used for console. 


USB wifi dongle is used for wifi AP (wireless router mode). In addition, Linux drivers support the product must be public.

USB wired NIC driver supports Linux as well in the price of the product.




2.Network Interface



I have planned as shown in the figure.


3.Set bridge


First thing to do is that you set the bridge. So that communication between the LAN eth1 and wlan0 available.


1)Install Bridge package
 $sudo apt-get install bridge-utils




2) /etc/network/interfaces Edit
Set the bridge br0 with wlan0,eth1.

/etc/network/interface
auto lo
auto br0
iface lo inet loopback
iface eth0 inet dhcp

iface br0 inet static
   bridge_ports eth1 wlan0
   address 192.168.0.1
   broadcast 192.168.0.255
   netmask 255.255.255.0



4.hostapd

1)Install Package
$sudo apt-get install hostapd

2)/usr/sbin/hostapd exchange
exchange old hostapd.

$wget http://www.daveconroy.com/wp3/wp-content/uploads/2013/07/hostapd.zip
$unzip hostapd.zip

Any chance that may have been in operation, hostapd to stop and exchange.

$sudo service hostapd stop
$sudo cp hostapd /usr/sbin/hostapd

3) /etc/hostapd/hostapd.conf 
lets you edit hostapd. Wlan0 is the interface, and the SSID is RPiAP. The password is PASSWORD.

rtl871xdrv is RTL8188CU hostapd of driver name. other parment so the technical part of the explanation. so I am no explain.


/etc/default/udhcpd
#created by ./install_ap.sh
interface=wlan0
bridge=br0
driver=rtl871xdrv
country_code=NZ
ctrl_interface=wlan0
ctrl_interface_group=0
ssid=RPiAP
hw_mode=g
channel=1
wpa=3
wpa_passphrase=PASSWORD
wpa_key_mgmt=WPA-PSK
wpa_pairwise=TKIP
rsn_pairwise=CCMP
beacon_int=1000
auth_algs=3
macaddr_acl=0
wmm_enabled=1
eap_reauth_period=360000000
       


5.udhcpd

1)Install Package
$sudo apt-get install udhcpd

2) /etc/default/udhcpd Edit
must shold edit the file first. Otherwise, an error occurs.  
Edited by red part.

/etc/default/udhcpd
# Comment the following line to enable
DHCPD_ENABLED="yes"

# Options to pass to busybox' udhcpd.
#
# -S    Log to syslog
# -f    run in foreground

DHCPD_OPTS="-S"
       

3) /etc/udhcpd.conf

Edit the file that udhcp.conf. 

It is a real udhcp AP is the most used.  The biggest feature is that the interface will be set to br0.

Gateway address is 192.168.0.1 is the address of br0.  

Edited by red part. 


/etc/udhcpd.conf
# Sample udhcpd configuration file (/etc/udhcpd.conf)

# The start and end of the IP lease block

start        192.168.0.100    #default: 192.168.0.20
end        192.168.0.200    #default: 192.168.0.254



# The interface that udhcpd will use

interface    br0        #default: eth0



# The maximim number of leases (includes addressesd reserved
# by OFFER's, DECLINE's, and ARP conficts

#max_leases    254        #default: 254


# If remaining is true (default), udhcpd will store the time
# remaining for each lease in the udhcpd leases file. This is
# for embedded systems that cannot keep time between reboots.
# If you set remaining to no, the absolute time that the lease
# expires at will be stored in the dhcpd.leases file.

#remaining    yes        #default: yes


# The time period at which udhcpd will write out a dhcpd.leases
# file. If this is 0, udhcpd will never automatically write a
# lease file. (specified in seconds)

#auto_time    7200        #default: 7200 (2 hours)


# The amount of time that an IP will be reserved (leased) for if a
# DHCP decline message is received (seconds).

#decline_time    3600        #default: 3600 (1 hour)


# The amount of time that an IP will be reserved (leased) for if an
# ARP conflct occurs. (seconds

#conflict_time    3600        #default: 3600 (1 hour)


# How long an offered address is reserved (leased) in seconds

#offer_time    60        #default: 60 (1 minute)

# If a lease to be given is below this value, the full lease time is
# instead used (seconds).

#min_lease    60        #defult: 60


# The location of the leases file

#lease_file    /var/lib/misc/udhcpd.leases    #defualt: /var/lib/misc/udhcpd.leases

# The location of the pid file
#pidfile    /var/run/udhcpd.pid    #default: /var/run/udhcpd.pid

# Everytime udhcpd writes a leases file, the below script will be called.
# Useful for writing the lease file to flash every few hours.

#notify_file                #default: (no script)

#notify_file    dumpleases    # <--- useful for debugging

# The following are bootp specific options, setable by udhcpd.

#siaddr        192.168.0.22        #default: 0.0.0.0

#sname        zorak            #default: (none)

#boot_file    /var/nfs_root        #default: (none)

# The remainer of options are DHCP options and can be specifed with the
# keyword 'opt' or 'option'. If an option can take multiple items, such
# as the dns option, they can be listed on the same line, or multiple
# lines. The only option with a default is 'lease'.

#Examles
opt    dns    8.8.8.8 8.8.8.4
option    subnet    255.255.255.0
opt    router    192.168.0.1
#opt    wins    192.168.10.10
#option    dns    129.219.13.81    # appened to above DNS servers for a total of 3
option    domain    local
option    lease    864000        # 10 days of secon
ds


# Currently supported options, for more info, see options.c
#opt subnet
#opt timezone
#opt router
#opt timesrv
#opt namesrv
#opt dns
#opt logsrv
#opt cookiesrv
#opt lprsrv
#opt bootsize
#opt domain
#opt swapsrv
#opt rootpath
#opt ipttl
#opt mtu
#opt broadcast
#opt wins
#opt lease
#opt ntpsrv
#opt tftp
#opt bootfile
#opt wpad

# Static leases map
#static_lease 00:60:08:11:CE:4E 192.168.0.54
#static_lease 00:60:08:11:CE:3E 192.168.0.44


After editing lets restart a service.

$sudo service udhcpd restart

6.iptables & ip4 forwarding

Linux iptable modification or rejection of the packet by the firewall or to provide services available. 
This is the /proc file are the same.  Linux, which application the user is to control the level in the Linux network capabilities.


1)iptable NAT
$sudo iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE

 2)ipv4 ip_forward
This sounds crazy, but, ip_forwarding  was denied permission to sudo . So let super user to activate ip_forwarding.
 
$su
#echo 1 > /proc/sys/net/ipv4/ip_forward




7.Extra edition

Every time you restart the Raspberry Pi, iptable command to that forwarding is suck. I edit the init file that  a boot command to be solved.


/etc/init.d/rc.local
#! /bin/sh
### BEGIN INIT INFO
# Provides:          rc.local
# Required-Start:    $all
# Required-Stop:
# Default-Start:     2 3 4 5
# Default-Stop:
# Short-Description: Run /etc/rc.local if it exist
### END INIT INFO


PATH=/sbin:/usr/sbin:/bin:/usr/bin

. /lib/init/vars.sh
. /lib/lsb/init-functions

do_start() {
        if [ -x /etc/rc.local ]; then
                [ "$VERBOSE" != no ] && log_begin_msg "Running local boot scripts (/etc/rc.local"
                /etc/rc.local
                ES=$?                                                                          
                [ "$VERBOSE" != no ] && log_end_msg $ES                                        
                return $ES                                                                     
        fi                                                                                     
}                                                                                              
                                                                                               
case "$1" in                                                                                   
    start)                                                                                     
        do_start                                                                               
        ;;                                                                                     
    restart|reload|force-reload)                                                               
        echo "Error: argument '$1' not supported" >&2                                          
        exit 3                                                                                 
        ;;                                                                                     
    stop)                                                                                      
        ;;                                                                                     
    *)                                                                                         
        echo "Usage: $0 start|stop" >&2                                                        
        exit 3                                                                                 
        ;;                                                                                     
esac                                                                                           
echo 1 > /proc/sys/net/ipv4/ip_forward                                                         
iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE 

       


8. network switch


Finally, connect eth1(RTL8185-USB internet adapter) to switch. end this work.


9.costs


list raspberry pi Ap generally AP
wireless LAN USB Card RTL8188CU[wlan0] $17 $0
wire LAN USB Card RTL8185[eth1] $12.7 $0
5port 100Mbps Switch $7.7 $0
Body $25 $12.7
Sum $62.4 $12.7


Raspberry AP is pefectly Crazy Idea.
if calculate the time,wage and added cost that. It is  over the $300.



10.Ending

It is characterized by many in South Korea utilizing multicast IP TV is. The AP that the Raspberry Pi is a traditional router performs multicast snooping and proxy in the proxy is thought possible. Further more that is going to run the daemon.

Also, when it comes to measuring the performance of AP Raspberry Pi is going to try.







라즈베리 파이 공유기


드디어 라즈베리 파이로 공유기 구축에 성공했습니다. 네트워크장비 업체에 있으면서 시간이 걸렸다는게 웃기는 일이기는 하지만, 처음 생각보다 성취감이 있군요.  계획은 벌써 2달도전에 했었지만, 이리저리 시간을 끌었습니다.

0. 목적

라즈베리 파이를 활용하여 기존의 무선공유기를 구현하는것이 목표입니다.




1. 디바이스 





  • 라즈베리파이
  • RTL8185(LAN-STAR LS-NAL11)
  • RTL8188CU(Wevo U150 - ) 
  • MAX232(rs232통신에서 5v와 3v를 맞춰주는 제품)



사용했던 제품은 위와 같습니다. USB유선랜카드는 LAN을 위해서 사용했고, wifi를 위해서 8188CU를 사용한 제품을 사용했습니다. 

MAX232는 네트워크를 초기화했을때에 ssh연결이 안되므로 사용했습니다. 혹시라도 네트워크설정을 잘못해줬다면, SD카드를 빼서 직접수정하는것도 방법입니다. 그러나 , 계속사용하면서 그렇게하기도 귀찮더군요.

wifi에 사용되는 USB wifi동글은 AP(무선공유기 모드)를 지원해야 합니다. 또한 리눅스 드라이버가 공개된 지원하는 제품이여야 합니다.

USB유선 랜카드도 마찬가지로 리눅스드라이버가 지원되는 제품이여야 합니다.



2. 네트워크 인터페이스 


그림과 같이 물리적 인터페이스를 구성했습니다.

또한, 그림과 같이 네트워크 인터페이스를 내부적으로 묶을것입니다.


3.bridge 설정


처음으로 할일은 브릿지를 설정해주는것입니다. 그래야 LAN eth1과 wlan0간의 통신이 가능합니다. 


1)패키지 설치
 $sudo apt-get install bridge-utils




2) /etc/network/interfaces 수정
브릿지에 해당하는 br0의 주소와 eth1,wlan0를 br0에 묶워줍니다.

/etc/network/interface
auto lo
auto br0
iface lo inet loopback
iface eth0 inet dhcp

iface br0 inet static
   bridge_ports eth1 wlan0
   address 192.168.0.1
   broadcast 192.168.0.255
   netmask 255.255.255.0



4.hostapd

1)패키지 설치
$sudo apt-get install hostapd

2)/usr/sbin/hostapd 교체
기존의 hostapd를 교체합니다. 

$wget http://www.daveconroy.com/wp3/wp-content/uploads/2013/07/hostapd.zip
$unzip hostapd.zip

혹시라도 작동중일지도 모르는, hostapd를 정지시키고 교체합니다.
$sudo service hostapd stop
$sudo cp hostapd /usr/sbin/hostapd

3) /etc/hostapd/hostapd.conf 
hostapd를 편집해줍니다. 인터페이스는 wlan0이며 SSID는 RPiAP이고 비밀번호는 PASSWORD입니다.
rtl871xdrv는 RTL8188CU의 hostapd를 위한드라이버명입니다. 이외에도 여러가지 사항들이 있지만,
wifi의 기술적인 부분이므로 설명은 생략합니다.

/etc/default/udhcpd
#created by ./install_ap.sh
interface=wlan0
bridge=br0
driver=rtl871xdrv
country_code=NZ
ctrl_interface=wlan0
ctrl_interface_group=0
ssid=RPiAP
hw_mode=g
channel=1
wpa=3
wpa_passphrase=PASSWORD
wpa_key_mgmt=WPA-PSK
wpa_pairwise=TKIP
rsn_pairwise=CCMP
beacon_int=1000
auth_algs=3
macaddr_acl=0
wmm_enabled=1
eap_reauth_period=360000000
       


5.udhcpd

1)패키지 설치
$sudo apt-get install udhcpd

2) /etc/default/udhcpd 수정
해당 파일을 먼저 편집해줘야 한다. 아니면, 에러가 발생한다.
빨간색이 편집한 부분입니다.

/etc/default/udhcpd
# Comment the following line to enable
DHCPD_ENABLED="yes"

# Options to pass to busybox' udhcpd.
#
# -S    Log to syslog
# -f    run in foreground

DHCPD_OPTS="-S"
       

3) /etc/udhcpd.conf

본격적인 udhcp.conf파일을 편집해주는 과정이다. 실제 가정용 AP에서 가장 많이 사용되는것이 udhcp이다.
가장 큰 특징은 인터페이스를 br0로 설정해주는것이다. ip분배계획은 2.의 인테페이스에 맞게 설정했다.
게이트 웨이주소는 br0의 주소 192.168.0.1이다.
빨간색이 편집한 부분입니다.
/etc/udhcpd.conf
# Sample udhcpd configuration file (/etc/udhcpd.conf)

# The start and end of the IP lease block

start        192.168.0.100    #default: 192.168.0.20
end        192.168.0.200    #default: 192.168.0.254



# The interface that udhcpd will use

interface    br0        #default: eth0



# The maximim number of leases (includes addressesd reserved
# by OFFER's, DECLINE's, and ARP conficts

#max_leases    254        #default: 254


# If remaining is true (default), udhcpd will store the time
# remaining for each lease in the udhcpd leases file. This is
# for embedded systems that cannot keep time between reboots.
# If you set remaining to no, the absolute time that the lease
# expires at will be stored in the dhcpd.leases file.

#remaining    yes        #default: yes


# The time period at which udhcpd will write out a dhcpd.leases
# file. If this is 0, udhcpd will never automatically write a
# lease file. (specified in seconds)

#auto_time    7200        #default: 7200 (2 hours)


# The amount of time that an IP will be reserved (leased) for if a
# DHCP decline message is received (seconds).

#decline_time    3600        #default: 3600 (1 hour)


# The amount of time that an IP will be reserved (leased) for if an
# ARP conflct occurs. (seconds

#conflict_time    3600        #default: 3600 (1 hour)


# How long an offered address is reserved (leased) in seconds

#offer_time    60        #default: 60 (1 minute)

# If a lease to be given is below this value, the full lease time is
# instead used (seconds).

#min_lease    60        #defult: 60


# The location of the leases file

#lease_file    /var/lib/misc/udhcpd.leases    #defualt: /var/lib/misc/udhcpd.leases

# The location of the pid file
#pidfile    /var/run/udhcpd.pid    #default: /var/run/udhcpd.pid

# Everytime udhcpd writes a leases file, the below script will be called.
# Useful for writing the lease file to flash every few hours.

#notify_file                #default: (no script)

#notify_file    dumpleases    # <--- useful for debugging

# The following are bootp specific options, setable by udhcpd.

#siaddr        192.168.0.22        #default: 0.0.0.0

#sname        zorak            #default: (none)

#boot_file    /var/nfs_root        #default: (none)

# The remainer of options are DHCP options and can be specifed with the
# keyword 'opt' or 'option'. If an option can take multiple items, such
# as the dns option, they can be listed on the same line, or multiple
# lines. The only option with a default is 'lease'.

#Examles
opt    dns    8.8.8.8 8.8.8.4
option    subnet    255.255.255.0
opt    router    192.168.0.1
#opt    wins    192.168.10.10
#option    dns    129.219.13.81    # appened to above DNS servers for a total of 3
option    domain    local
option    lease    864000        # 10 days of secon
ds


# Currently supported options, for more info, see options.c
#opt subnet
#opt timezone
#opt router
#opt timesrv
#opt namesrv
#opt dns
#opt logsrv
#opt cookiesrv
#opt lprsrv
#opt bootsize
#opt domain
#opt swapsrv
#opt rootpath
#opt ipttl
#opt mtu
#opt broadcast
#opt wins
#opt lease
#opt ntpsrv
#opt tftp
#opt bootfile
#opt wpad

# Static leases map
#static_lease 00:60:08:11:CE:4E 192.168.0.54
#static_lease 00:60:08:11:CE:3E 192.168.0.44


편집이 끝난후에 서비스를 새로 시작해줍니다.

$sudo service udhcpd restart

6.iptables & ip4 forwarding

iptable은 리눅스에서 패킷들의 변형이나 거부를 함으로서 서비스를 제공하거나 방화벽을 제공 가능하다.
이것은 /proc의 파일들도 마찬가지입니다. 

이 2가지는 리눅스에서 사용자가 application 레벨에서 리눅스의 네트워크를 제어하는 기능을 제공한다.

1)iptable NAT
$sudo iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE

 2)ipv4 ip_forward
이상하게 들리겠지만, ip_forwarding은 sudo를 사용해도 허가거부가 있었다. 그래서 super user로 ip_forwarding을 활성화 시켰다.
$su
#echo 1 > /proc/sys/net/ipv4/ip_forward




7.번외편

라즈베이 파이를 재시작할때 마다 해당되는 iptable명령과 forwarding을 해주는것은 귀찮은 일이다.
이것들은 init파일을 편집해줌으로서 부팅때마다 명령해주는것으로  해결했다.


/etc/init.d/rc.local
#! /bin/sh
### BEGIN INIT INFO
# Provides:          rc.local
# Required-Start:    $all
# Required-Stop:
# Default-Start:     2 3 4 5
# Default-Stop:
# Short-Description: Run /etc/rc.local if it exist
### END INIT INFO


PATH=/sbin:/usr/sbin:/bin:/usr/bin

. /lib/init/vars.sh
. /lib/lsb/init-functions

do_start() {
        if [ -x /etc/rc.local ]; then
                [ "$VERBOSE" != no ] && log_begin_msg "Running local boot scripts (/etc/rc.local"
                /etc/rc.local
                ES=$?                                                                          
                [ "$VERBOSE" != no ] && log_end_msg $ES                                        
                return $ES                                                                     
        fi                                                                                     
}                                                                                              
                                                                                               
case "$1" in                                                                                   
    start)                                                                                     
        do_start                                                                               
        ;;                                                                                     
    restart|reload|force-reload)                                                               
        echo "Error: argument '$1' not supported" >&2                                          
        exit 3                                                                                 
        ;;                                                                                     
    stop)                                                                                      
        ;;                                                                                     
    *)                                                                                         
        echo "Usage: $0 start|stop" >&2                                                        
        exit 3                                                                                 
        ;;                                                                                     
esac                                                                                           
echo 1 > /proc/sys/net/ipv4/ip_forward                                                         
iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE 

       


8. network switch

마지막으로 eth1으로 사용되는 USB인터넷 어댑터 RTL8185에 스위치를 연결한다면 기존의 공유기와 기본적으로  같은 기능을 하게 됩니다.



9.비용결산


항목 라즈베리파이 AP 비용 기존공유기 비용
무선랜 RTL8188CU[wlan0] ₩17000 ₩0
유선 랜카드 RTL8185[eth1] ₩12700 ₩0
5포트 100Mbps 스위치 ₩7700 ₩0
본체 ₩25000 ₩12700
합계 ₩62400 ₩12700


완벽하게 라즈베리 파이로 공유기를 만드는게 뻘짓입니다. ㅋㅋㅋㅋㅋㅋㅋㅋㅋ
노력은 계산에 안들어가서 망정이지  인력비로 계산했다면 20만원 넘어갑니다 ㅋㅋㅋㅋ


10. 마치며

한국에서 특징적으로 많은것이 멀티캐스트를 활용한 IP TV입니다. 그리고, 해당되는 라즈베리파이 AP도 기존의 공유기가 수행하는 멀티캐스트 스누핑과 프록시중에서 프록시는 가능할거라고 생각합니다. 좀더 나아가서 해당되는 데몬을 실행할 예정입니다.

또한 라즈베리 파이AP의 성능에 관해서 측정해볼 예정입니다.







2014년 7월 13일 일요일

raspberry ap -1

 http://www.daveconroy.com/turn-your-raspberry-pi-into-a-wifi-hotspot-with-edimax-nano-usb-ew-7811un-rtl8188cus-chipset/

 

 

Prerequisites

The first thing you need to do is make sure you have an existing wired connection to your rPi. After that, you need to install the following packages.
sudo apt-get install bridge-utils hostapd
The whole crux of the issue is that it is the apt hosted copy of hostapd that is not compatible with the RTL8188CUS chipset. But, thanks to the Edimax team, I’ve got a replacement hostapd binary to resolve this issue. This tutorial will not work without it.
To download and replace the installed binary version of hostapd we just installed, issue the following commands:
wget http://www.daveconroy.com/wp3/wp-content/uploads/2013/07/hostapd.zip
unzip hostapd.zip 
sudo mv /usr/sbin/hostapd /usr/sbin/hostapd.bak
sudo mv hostapd /usr/sbin/hostapd.edimax 
sudo ln -sf /usr/sbin/hostapd.edimax /usr/sbin/hostapd 
sudo chown root.root /usr/sbin/hostapd 
sudo chmod 755 /usr/sbin/hostapd
*Note, some people don’t like the idea of installing from untrusted 3rd parties, so if If would rather compile your own binary, you can download the realtek driver here . You will have to navigate to the ~/RTL8188C_8192C_USB_linux_v3.4.4_4749.20121105/wpa_supplicant_hostapd/wpa_supplicant_hostapd-0.8/hostapd and run a make, make install, then hostapd like i did above.

Bridge the Network Connections

Now that we have the proper hostapd installed, we need to create a bridge between our ethernet connection and our Edimax Wireless card. To do this, we need to edit our network interfaces:
sudo nano /etc/network/interfaces
To avoid any conflicts, you need to delete or comment out(#) any lines conatining wlan0 and then add the following text to bridge the connections, assuming your ethernet and wireless adapters are named eth0 and wlan0( use ifconfig -a to check)
auto br0
iface br0 inet dhcp
bridge_ports eth0 wlan0

The resulting file should look like this:
#loopback adapter
auto lo
iface lo inet loopback

#wired adapter
iface eth0 inet dhcp
#bridge
auto br0
iface br0 inet dhcp
bridge_ports eth0 wlan0

Configuring Hostapd

Now that our interfaces are setup, we need to configure hostapd. To do so, create the following file
sudo nano /etc/hostapd/hostapd.conf
with the following contents:
interface=wlan0
driver=rtl871xdrv
bridge=br0
ssid=DaveConroyPi
channel=1
wmm_enabled=0
wpa=1
wpa_passphrase=ConroyPi
wpa_key_mgmt=WPA-PSK
wpa_pairwise=TKIP
rsn_pairwise=CCMP
auth_algs=1
macaddr_acl=0

2014년 6월 28일 토요일

라즈베리 파이 라우터에 대해서...



노력에 가치를 정할수 있을까? 이것에 대한 간단한 답은 있다. 내가 월요일부터 금요일까지 회사에서도 노동을 하고 받은 보수가 그것에 대한 척도가 될수있을것이다.

노동은 분명히 가치있는일이다. 이것은 부정할수 없다. 그렇지만, 내가 했던 노동은 아니지만 노력이 쓸모없는것이라면 어떻게 될까?

현재 구상하는 개인프로젝트에 관한 이야기이다. 과거에 라즈베리 파이를 라우터로 사용한다는 이야기가 구글플러스 라즈베리파이의 커뮤니티에 나왔었다.

이것에 대해서 기뻐했던 사람들이 있었지만, 나는 조금은 부정적이었다. 이유는 라즈베리파이를 라우터로 사용하는것은 기존의 네트워크장비(스위치,공유기,라우터)로 사용한다는것을 의미하지만 그것이 이미 라즈베리파이보다 값싼 장비보다 성능이 못할가능성이 아주 높기때문이다.

왜 라즈베리파이를 네트워크장비로 사용하는것이 가격대비 성능이 떨어지냐 하면, 라즈베리파이로는 같은 가격의 네트워크장비의 하드웨어 트래픽처리 성능을 따라잡을수 없기때문이다.


그렇게기 때문에, 라즈베리파이로 네트워크장비를 대체하는 프로젝트를 완성했다고 쳐도 만든자신조차 이것을 사용할 가능성이 없기때문이다.


이모든것을 알고있지만, 해보자... 해보고 생각하련다...

2014년 6월 14일 토요일

make up Home network







I finally make up my home network. it is very comfortable and useful. the APs link separated device.



1) Android Settop
this device connected TV on HDMI. and samba client of Raspberry Pi Samba Server.


2,3) Access Point
AP must support igmp snooping for IPTV.


4)IP TV Settop
IPTV media packet use muticast. but, muticast is layer 2. AP igmp soonping is important.

5)HDMI TV


6)Lapttop
control Device.

7)Raspberry pi
my pi work Server. samba/ torrent Daemon /DLNA DMS

8)SmartPhone
control Device.



Living room / my room pi



2014년 5월 25일 일요일

raspberry pi - NAS구축



딱히 대단할것 없는 rapsberry pi - NAS 구축입니다. 저는 Debian wheezy를 사용했으며,
대부분의 사항은 기존의 Debian의 서버구축과 비슷하기에 생략합니다.




대략 구축한 개념은 위와 같습니다. AP(공유기)에 라즈베리 파이를 유선 인터넷으로 연결하고, 라즈베리에는 USB 외장하드가 연결되어 있습니다.또한 텔레비젼에는 DLNA기능이 있어서 pi의 동영상을 무선으로 보는것이 가능합니다.





여기까지는 별문제가 없지만, USB외장하드디스크의 경우에 전원문제가 발생합니다. 따라서 무조건 5V-2A USB어댑터를 사용하는것이 필수적입니다. 위 사진과 같은 5V-2A 어댑터를 말이죠. 

또한 발열 문제로서 방열판을 부착하는것을 추천합니다. 논외적으로 wifi를 사용할수도 있습니다. 추천제품은 RTL8188CU를 사용하는 제품들입니다. 저는 WevoU150을 샀지만, n100mini가 더 싸게 나왔군요. 뭐 제품선택은 알아서...






보시다시피 아래에 USB외장하드가 있고, 라즈베리가 연결되어 있습니다. 라즈베리에는 인터넷 게이블이 공유기와 연결되어있죠. 개인적으로 pogoplug가 고장난 관계로 라즈베리를 하나더 구입하여 NAS를 꾸며봤습니다. PogoPlug도 나름의 강점을 가지지만, 개인적으로 돈을 좀더 투자해서라도 라즈베리파이를 사용하는것을 추천드림니다. 

이유는 포고플러그같은 경우에 외장하드는 전력문제인지 모르겠지만, 원인을 알수없이 동작을 중지하거나 메모리가 너무 적기때문에 사용에 제한이 너무 많다는점때문입니다.


dlan같은 경우에는 잘찾아서 하세영 ㅇㅅㅇ