인터넷의 성공으로 TCP/IP 프로토콜은 전세계적인 통신 표준이 되었다. TCP/IP는 인터넷을 통한 웹 페이지 전송, 이 메일 전송, 파일 전송, 피어투피어 네트워킹(peer-to-peer networking)을 위해 사용되는 프로토콜의 기반이다. 임베디드 시스템에서 인트라넷 또는 인터넷에 시스템을 연결하는 것이 가능하다. 완전한 TCP/IP를 지원하는 임베디드 디바이스들은 첫번째 클래스 네트워크 구성이 될것이다. 따라서 네트워크에서 다른 호스트와 통신하는 것이 가능하다.
Traditional TCP/IP implementations have required far too much resources both in terms of code size and memory usage to be useful in small 8 or 16-bit systems. Code size of a few hundred kilobytes and RAM requirements of several hundreds of kilobytes have made it impossible to fit the full TCP/IP stack into systems with a few tens of kilobytes of RAM and room for less than 100 kilobytes of code.
전통적인 TCP/IP 구현은 작은 8비트 또는 16비트 시스템에서 코드사이즈와 메모리 사용에서 너무 많은 자원을 요구 해왔다. 몇 백 킬로 바이트 코드사이즈와 램의 요구는 수십 킬로바이트 램과 100킬로바이트보다 작은 메모리를 가진 시스템에서 풀사이즈의 TCP/IP스택을 구현하는 것을 불가능 하게 했다.
The uIP implementation is designed to have only the absolute minimal set of features needed for a full TCP/IP stack. It can only handle a single network interface and contains only a rudimentary UDP implementation, but focuses on the IP, ICMP and TCP protocols. uIP is written in the C programming language.
uIP 구현은 전체 TCP/IP스택에서 필요한 최소한의 부분만 가지고 있도록 설계되었다. uIP는 단일 네트워크 인터페이스만 다룰 수 있고 UDP 구현을 포함하고 있고 IP, ICMP, TCP에 초점이 맞추어 져 있고 C언어로 만들어져 있다.
Many other TCP/IP implementations for small systems assume that the embedded device always will communicate with a full-scale TCP/IP implementation running on a workstation-class machine. Under this assumption, it is possible to remove certain TCP/IP mechanisms that are very rarely used in such situations. Many of those mechanisms are essential, however, if the embedded device is to communicate with another equally limited device, e.g., when running distributed peer-to-peer services and protocols. uIP is designed to be RFC compliant in order to let the embedded devices to act as first-class network citizens. The uIP TCP/IP implementation that is not tailored for any specific application.
작은 시스템을 위한 다른 많은 TCP/IP 구현들은 임베디드 디바이스가 항상 웍크스테이션 머신에서 동작하는 풀-스케일 TCP/IP 구현을 가지고 통신할 것이라고 가정한다. 이런 가정하에, 그런상황에서 거의 사용되지 않는 TCP/IP 메커니즘을 제거 할 수 있다. 임베디드 디바이스가 똑같이 다른 제한적인 디바이스와 통신한다면 다른 많은 메커니즘들을 꼭 필요하다. uIP는 RFC와 호환되도록 설계되었다.
IP 주소를 MAC 주소로 전환하는 ARP와 같은 하위 레벨 프로토콜에서 이메일 전송에 사용되는 SMTP와 같은 응용 레벨 프로토콜까지, 전체 TCP/IP는 많은 프로토콜로 이루어져 있다. uIP는 대부분 TCP와 IP 프로토콜에 집중되어 있고 상위 계층 프로토콜은 어플리케이션으로써 참조된다. 하위 계층 프로토콜들은 하드웨어나 펌웨어로 구현되고 네트워크 디바이스 드라이버에의해 제어되는 네트워크 디바이스로써 참조된다.
TCP provides a reliable byte stream to the upper layer protocols. It breaks the byte stream into appropriately sized segments and each segment is sent in its own IP packet. The IP packets are sent out on the network by the network device driver. If the destination is not on the physically connected network, the IP packet is forwarded onto another network by a router that is situated between the two networks. If the maximum packet size of the other network is smaller than the size of the IP packet, the packet is fragmented into smaller packets by the router. If possible, the size of the TCP segments are chosen so that fragmentation is minimized. The final recipient of the packet will have to reassemble any fragmented IP packets before they can be passed to higher layers.
TCP는 상위 계층 프로토콜에 신뢰성 있는 바이트 스트림을 제공한다. TCP는 바이트 스트림을 적당한 사이즈의 세그먼트로 쪼개고 각 세그먼트는 IP 패킷으로 보내진다. IP 패킷은 네트워크 디바이스 드라이버에 의해 네트워크을 통해 전송된다. 목적지가 물리적으로 연결된 네트워크에 있지 않으면 라우터에 의해 다른 네트워크으로 포워딩 된다. 만약 다른 네트워크의 최대 패킷 사이즈가 IP패킷의 사이즈보다 작다면, 그 패킷은 라우터에 의해 더 작은 패킷으로 절단된다. 가능하면 TCP 세그먼트의 사이즈는 단편이 최소화 되도록 선택된다. 패킷이 마지막으로 수신되면 상위 계층으로 전달하기 전에 절단된 IP패킷을 재 조립한다.
The formal requirements for the protocols in the TCP/IP stack is specified in a number of RFC documents published by the Internet Engineering Task Force, IETF. Each of the protocols in the stack is defined in one more RFC documents and RFC1122 collects all requirements and updates the previous RFCs.
TCP/IP 스택에서 프로토콜을 위한 일반적인 요구사항은 RFC 문서 번호로 규정된다. 스택에서 각 프로토콜은 하나 이상의 RFC 문서에 정의 되어 있다. RFC1122는 모든 요구사항들을 모아 놓았고 이전 RFC를 업데이트 했다.
The RFC1122 requirements can be divided into two categories; those that deal with the host to host communication and those that deal with communication between the application and the networking stack. An example of the first kind is "A TCP MUST be able to receive a TCP option in any segment" and an example of the second kind is "There MUST be a mechanism for reporting soft TCP error conditions to the application." A TCP/IP implementation that violates requirements of the first kind may not be able to communicate with other TCP/IP implementations and may even lead to network failures. Violation of the second kind of requirements will only affect the communication within the system and will not affect host-to-host communication.
RFC1122 요구사항들은 두개의 카테고리로 나뉜다. 호스트와 호스트끼리의 통신을 다루는 것과 어플리케이션과 네트워크 스택사이의 통신을 다루는 것이다. 첫 번째 종류의 예는 “TCP MUST는 어떤 세그먼트에 TCP 옵션을 수신할수 있어야 한다.” 와 두번째 예는 “MUST 는 TCP 에러 상태를 어플리케이션에게 알려줄수 있는 메케니즘이 있다.” 첫 번째 요구사항을 어기는 TCP/IP 구현은 다른 TCP/IP 구현부와 통신할 수 없고 네트워크 실패를 초래 한다. 두번째 종류의 요구사항을 어기는 것은 시스템 내에서 단지 통신에 영향을 미치고 호스트와 호스트 사이 통신에는 영향을 미치지 않는다.
In uIP, all RFC requirements that affect host-to-host communication are implemented. However, in order to reduce code size, we have removed certain mechanisms in the interface between the application and the stack, such as the soft error reporting mechanism and dynamically configurable type-of-service bits for TCP connections. Since there are only very few applications that make use of those features they can be removed without loss of generality.
uIP에서 호스트와 호스트 사이 통신에 영향을 미치는 RFC요구사항들은 구현되어 있다. 그러나 코드사이즈를 줄이기 위해, 에러를 알리는 메커니즘과 TCP연결을 위해 동적으로 구성가능한 서비스타입 비트들과 같은 어플리케이션과 스택사이의 인터페이스에 특정 메커니즘은 제거 하였다.
uIP에서 추구하는 아키텍쳐에서 램은 매우 귀한 자원이다. 몇 킬로 바이트의 램으로도 TCP/IP 스택 구현이 가능하지만, 전통적인 TCP/IP에서의 메커니즘에서는 직접 적용될 수 없다.
The uIP stack does not use explicit dynamic memory allocation. Instead, it uses a single global buffer for holding packets and has a fixed table for holding connection state. The global packet buffer is large enough to contain one packet of maximum size. When a packet arrives from the network, the device driver places it in the global buffer and calls the TCP/IP stack. If the packet contains data, the TCP/IP stack will notify the corresponding application. Because the data in the buffer will be overwritten by the next incoming packet, the application will either have to act immediately on the data or copy the data into a secondary buffer for later processing. The packet buffer will not be overwritten by new packets before the application has processed the data. Packets that arrive when the application is processing the data must be queued, either by the network device or by the device driver. Most single-chip Ethernet controllers have on-chip buffers that are large enough to contain at least 4 maximum sized Ethernet frames. Devices that are handled by the processor, such as RS-232 ports, can copy incoming bytes to a separate buffer during application processing. If the buffers are full, the incoming packet is dropped. This will cause performance degradation, but only when multiple connections are running in parallel. This is because uIP advertises a very small receiver window, which means that only a single TCP segment will be in the network per connection.
uIP는 스택은 명시적으로 동적 메모리 할당을 사용하지 않는다. 대신, 패킷을 저장하기 위해 전역 버퍼를 사용하고 연결 상태를 저장하기 위해 고정된 테이블을 가진다. 전역 패킷 버퍼는 하나의 최대 사이즈의 패킷을 담기에 충분히 크다. 패킷이 네트워크으로부터 수신되었을 때 디바이스 드라이브는 그 패킷을 전역 버퍼에 넣고 TCP/IP스택을 호출한다. 패킷이 데이터를 가지고 있다면, TCP/IP 스택은 해당 어플리케이션에게 알린다. 버퍼에 있는 데이터는 다음에 오는 패킷에 의해 덮어 써질 수 있기 때문에, 어플리케이션은 즉시 데이터를 즉시 처리하거나 나중에 처리하기 위해 데이터를 다른 버퍼에 복사해 두어야 한다. 패킷 버퍼는 어플리케이션이 데이터를 처리하기 전에 새로운 패킷에 의해 덮어써 지지 않을 것이다. 어플리케이션이 데이터를 처리하고 있는 중에 도착한 패킷은 네트워크 디바이스나 디바이스 드라이버에 의해 큐잉 되어야 한다. 대부분의 싱글-칩 이더넷 컨트롤러는 최소 4개의 최대 길이의 프레임을 담을 수 있는 온-칩(On-Chip) 버퍼를 가지고 있다. RS-232 포트와 같이 프로세서가 다루는 디바이스는 어플리케이션이 처리하고 있는 중에, 입력되는 바이트를 독립된 버퍼에 복사해 둔다. 만약 버퍼가 꽉 찾다면, 수신된 패킷은 버려진다. 이것은 다중 연결이 병렬로 동작 될 때 성능을 저하시키게 된다. 이것은 uIP가 작은 수신 윈도우를 가지고 있기 때문이고 네트워크 연결당 하나의 TCP세그먼트가 있어야 된다는 것을 의미한다.
In uIP, the same global packet buffer that is used for incoming packets is also used for the TCP/IP headers of outgoing data. If the application sends dynamic data, it may use the parts of the global packet buffer that are not used for headers as a temporary storage buffer. To send the data, the application passes a pointer to the data as well as the length of the data to the stack. The TCP/IP headers are written into the global buffer and once the headers have been produced, the device driver sends the headers and the application data out on the network. The data is not queued for retransmissions. Instead, the application will have to reproduce the data if a retransmission is necessary.
uIP에서, 수신 패킷을 위해 사용되는 같은 전역 패킷 버퍼는 송신 데이터의 TCP/IP 헤더를 위해 사용된다. 어플리케이션이 동적 데이터를 송신한다면, 어플리케이션은 임시 저장 버퍼로써 헤더를 위해 사용되지 않는 전역 패킷 버퍼의 일부를 사용한다. 데이터를 송신하기 위해, 어플리케이션은 데이터 포인트와 데이터의 길이를 스택에 전달 한다. 전역 버퍼에 TCP/IP 헤더를 저장하고 헤더가 만들어 지면 디바이스 드라이버는 헤더와 어플리케이션 데이터를 네트워크으로 전송한다. 데이터는 재전송을 위해 큐잉되지 않는다. 대신, 어플리케이션은 재전송이 필요하다면 데이터를 재생성 한다.
The total amount of memory usage for uIP depends heavily on the applications of the particular device in which the implementations are to be run. The memory configuration determines both the amount of traffic the system should be able to handle and the maximum amount of simultaneous connections. A device that will be sending large e-mails while at the same time running a web server with highly dynamic web pages and multiple simultaneous clients, will require more RAM than a simple Telnet server. It is possible to run the uIP implementation with as little as 200 bytes of RAM, but such a configuration will provide extremely low throughput and will only allow a small number of simultaneous connections.
uIP의 전체 메모리 사용량은 구현부가 돌아가게 되는 디바이스 어플리케이션에 의존적이다. 메모리 구성은 시스템이 다룰 수 있는 트래픽(traffic) 양과 최대로 동시에 연결 할 수 있는 양을 결정 짓는다. 큰 이 메일을 보내고 동시에 동적 웹 페이지를 가지고 있는 웹 서버가 동작하고 있는 디바이스는 간단한 텔넷 서버보다 많은 램이 요구된다. uIP는 200바이트 램으로도 동작될 수 있다. 그러나 그러한 구성은 낮은 처리량을 제공하고 동시 접속수를 작게 한다.
응용 프로그램 인터페이스는 응용 프로그램이 TCP/IP 스택과 상호 작용하는 방법을 정의하고 있다. TCP/IP에서 사용되는 대부분은 유닉스 시스템에서 사용되는 BSD 소켓이고 마이크로 소프트 윈도우의 WinSock API에 영향을 주었다. 소켓 API는 stop-and-wait 방식을 사용하기 때문에 멀티타스킹 오퍼레이션 시스템에서 지원되는 것이 요구된다. 타스크 관리의 오버헤드 때문에, 타스크를 위한 문맥 교환과 스택 공간 할당은 uIP 타켓 아키텍쳐에서는 오버헤드가 크다. BSD 소켓 인터페이스는 우리의 목적에는 적당하지 않다.
Instead, uIP uses an event driven interface where the application is invoked in response to certain events. An application running on top of uIP is implemented as a C function that is called by uIP in response to certain events. uIP calls the application when data is received, when data has been successfully delivered to the other end of the connection, when a new connection has been set up, or when data has to be retransmitted. The application is also periodically polled for new data. The application program provides only one callback function; it is up to the application to deal with mapping different network services to different ports and connections. Because the application is able to act on incoming data and connection requests as soon as the TCP/IP stack receives the packet, low response times can be achieved even in low-end systems.
대신, uIP는 어플리케이션이 어떠한 이벤트에 응답으로 호출되는 이벤트 드리븐(event driven) 인터페이스를 사용한다. uIP 위에서 동작되는 어플리케이션은 어떠한 이벤트 응답으로 uIP에의해 호출되는 C함수로 구현되어 있다. uIP는 데이터가 수신되었을 때, 데이터가 연결된 반대편에 성공적으로 전달 되었을 때, 새로운 연결이 셋업 되었을 때, 데이터가 재전송 되었을 때, 어플리케이션을 호출한다. 어플리케이션은 데이터를 주기적으로 폴링한다. 응용 프로그램은 단지 하나의 콜백 함수를 제공한다.
uIP is different from other TCP/IP stacks in that it requires help from the application when doing retransmissions. Other TCP/IP stacks buffer the transmitted data in memory until the data is known to be successfully delivered to the remote end of the connection. If the data needs to be retransmitted, the stack takes care of the retransmission without notifying the application. With this approach, the data has to be buffered in memory while waiting for an acknowledgment even if the application might be able to quickly regenerate the data if a retransmission has to be made.
uIP는 재전송 할 때 어플리케이션에게 도움을 요청하는 점에서 다른 스택들과 차이점이 있다. 다른 TCP/IP스택은 데이타가 반대편에 성공적으로 전달되었다고 판단 될때 까지 데이타를 메모리에 담고 있다. 만약 데이타가 재전송 되야한다면 스택은 어플리케이션과 상관없이 재전송을 수행한다. 따라서 어플리케이션이 급히 재전송을 수행하려해도 메모리안에 ACK메시지를 기다리는 데이터 때문에 재전송을 수행하지 못하는 경우가 생기게 된다.
In order to reduce memory usage, uIP utilizes the fact that the application may be able to regenerate sent data and lets the application take part in retransmissions. uIP does not keep track of packet contents after they have been sent by the device driver, and uIP requires that the application takes an active part in performing the retransmission. When uIP decides that a segment should be retransmitted, it calls the application with a flag set indicating that a retransmission is required. The application checks the retransmission flag and produces the same data that was previously sent. From the application's standpoint, performing a retransmission is not different from how the data originally was sent. Therefore the application can be written in such a way that the same code is used both for sending data and retransmitting data. Also, it is important to note that even though the actual retransmission operation is carried out by the application, it is the responsibility of the stack to know when the retransmission should be made. Thus the complexity of the application does not necessarily increase because it takes an active part in doing retransmissions.
메모리 사용을 줄이기 위해서, uIP는 어플리케이션과 함께 재전송을 수행한다. uIP가 재전송하려고 할때, 재전송 요청 플래그와 함께 어플리케이션을 호출한다.. 어플리케이션은 재전송 플래그를 보고 앞서보낸 데이터와 같은 데이터를 생성한다. 어플리케이션의 입장에서는 재전송을 수행하는 것은 원래 데이터 전송하는것과 다르지 않게 여기기 때문에 데이터전송과 재전송의 코드가 같다. 따라서 uIP스택이 재전송 요청만 해준다면, 어플리케이션은 별다른 코드 복잡성없이 재전송을 수행하게 된다.
Application events
The application must be implemented as a C function, UIP_APPCALL(), that uIP calls whenever an event occurs. Each event has a corresponding test function that is used to distinguish between different events. The functions are implemented as C macros that will evaluate to either zero or non-zero. Note that certain events can happen in conjunction with each other (i.e., new data can arrive at the same time as data is acknowledged).
uIP는 이벤트가 발생될때마다 어플리케이션의 UIP_APPCALL()을 호출한다. 각각의 이벤트들 마다 테스트함수를 둬서 이벤트들을 구분한다. 이 함수는 C메크로 처럼 구현되어져 zore 또는 non-zero를 리턴한다. 주의해야 할 경우는 어떤 이벤트들은 동시 다발적으로 일어날 수 있다는 것이다.(예를 들어,새로운 데이타가 ACK메시지와 동시에 도착한다.)
어플리케이션이 uIP에 의해 호출될때, 전역변수 uip_conn는 현재 연결을 핸들하기위해 구조체 uip_conn를 포인트한다. 이를 "current connection"이라고 부른다. uip_conn에 있는 필드들은 현재 접속이 사용되어 질수있도록, 서비스들을 구별하기 위해서,또는 연결된 접속의 IP의 주소를 체크할 용도로 사용되어진다. 전형적으로 uip_conn->lport (local TCP 포트넘버)는 어느 서비스가 제공되는지 지정한다. 예를 들어 uip_conn->lport가 80으로 지정되있다면 어플리케이션은 HTTP 서비스를 할것이고, 23으로 지정되있다면 TELNET서비스를 할 것이다.
만약 uIP의 테스트 함수 uip_newdata()이 넌제로면, 원격지의 호스트가 새로운 데이터를 전송한 것이다. uip_appdata 포인터는 실제 데이터를 포인트한다. 데이터의 크기는 uIP 함수uip_datalen()를 통해 얻는다. 그 데이터는 uIP에 의해 저장되지는 않지만 어플리케이션이 들어온 데이터에 직접 반응하거나 추후에 처리하기위해 복사한 후에 덮어씌어 진다.
데이터를 보낼때 uIP는 어플리케이션에 의해 계산된 데이터의 크기를 적용한다. 버퍼크기는 메모리 설정에 의해 결정되기 때문에 보내는 쪽의 모든 데이터는 받는쪽에서 도착하지 않을 수가 있다. 그리고 uip_mss()함수를 사용해서 보낼 수 있는 데이터의 크기가 얼마인지 알 수있다.
The application sends data by using the uIP function uip_send(). The uip_send() function takes two arguments; a pointer to the data to be sent and the length of the data. If the application needs RAMspace for producing the actual data that should be sent, the packet buffer (pointed to by the uip_appdata pointer) can beused for this purpose.
어플리케이션은 uip_send()함수를 사용해서 데이터를 전송한다. 이 함수는 두개의 매개변수를 갖는데 하나는 데이터의 포인터이고, 다른 하나는 데이터의 크기이다. 어플리케이션이 데이터를 전송하기위한 RAM공간이 필요하다면 패킷버퍼(uip_appdata포인터가 포인트하는 공간)가 이 용도로 사용되어진다.
The application can send only one chunk of data at a time on a connection and it is not possible to call uip_send() more than once per application invocation; only the data from the last call will be sent.
어플리케이션은 하나의 연결에 한개의 data chunk를 전송할수있다. 어플리케이션 당 한번 이상 uip_send()함수를 호출 할 수 없다.
재전송은 주기적인 TCP타이머에 의해 동작한다. 전송할때 마다 주기적 타이머가 호출되고, 재전송타이머가 줄어들기 시작한다. 재전송 타이머가 0이되면 재전송루틴이 수행된다. uIP는 디바이스 드라이버를 통해 전송된 후의 패킷은 가지고 있지 않는 대신에 어플리케이션에게 재전송을 요청하는데, uip_rexmit()함수를 통해서 재전송 요청 플래그를 세팅한다.
The application must check the uip_rexmit() flag and produce the same data that was previously sent. From the application's standpoint, performing a retransmission is not different from how the data originally was sent. Therefor, the application can be written in such a way that the same code is used both for sending data and retransmitting data. Also, it is important to note that even though the actual retransmission operation is carried out by the application, it is the responsibility of the stack to know when the retransmission should be made. Thus the complexity of the application does not necessarily increase because it takes an active part in doing retransmissions.
어플리케이션은 uip_rexmit()로 플래그를 체크하고 이전에 전송한 데이터와 똑같은 데이터를 만든다. 어플리케이션의 관점에서 보면,재전송을 수행하는것은 데이터를 전송하는 루틴과 차이를 두지 않기 때문에 같은 코드를 사용한다. 또한 중요한것은 재전송 여부의 판단을 스택에서 하기때문에 어플리케시션의 복잡성(complexity)은 증가 되지 않는다.
어플리케이션은 현재의 연결을 uip_close()함수를 호출하므로써 연결을 깨끗하게 close한다. 에러를 보고하기 위해서는 어플리케이션은 uip_abort()함수로 연결을 취소한다. 만약 상대편에 의해서 연결이 종료되었다면 , uip_closed() 테스트 함수의 리턴값은 1(true)가 된다. 이경우 어플리케이션에서는 연결종료를 따로 처리할 필요가 없다.
연결에서 발생 될 수 있는 치명적인 에러가 두개 있다. 상대편 호스트에 의해 취소된 연결이거나, 재전송 할 때 마지막 데이터의 타이머가 0이 되서 취소된 경우이다. uIP는 어플리케이션을 호출하므로써 이 에러들을 보고한다. 어플리케이션은 uip_aborted(), uip_timedout() 이 두가지 테스트 함수를 사용해서 에러여부를 테스트한다.
연결이 한가할때, uIP는 주기적 타이머를 사용해서 어플리케이션을 검사(poll)한다. 그 어플리케이션은 uip_poll()이란 테스트 함수를 사용해서 uIP가 어플리케이션을 검사중인지 아닌지를 테스트한다. 폴링에는 두가지 목적을 갖는다. 첫번째는 어플리케이션이 주기적으로 연결의 한가함을 알게함으로서, 너무 많이 쉬고있는 연결들을 close시키기 위함이다. 다른 목적은 어플리케이션이 새로운 데이터를 전송하게 함에 있다. 어플리케이션은 오직 uIP에 의해 호출될때 만 데이터를 전송할수있기 때문에 검사신호(poll event)는 연결이 idle상태를 깨워서 데이터를 전송하게 할수있는 유일한 방법이된다.
uIP는 리스닝 TCP포트의 리스트를 가지고있다. uip_listen()함수를 통해서 새로운 포트를 열 수 있다. 리스닝 포트로 연결요청이 들어왔을때, uIP는 새로운 연결을 설정하고 어플리케이션 함수를 호출한다. 어플리케이션은 테스트 함수uip_connected()를 통해서 연결요청 여부를 테스트한다. true면 새로운 연결이 만들어 진것이다. 어플리케이션은 uip_conn구조체의 필드값 lport를 체크함으로서 새로운 연결에 사용되는 포트가 몇번인지 알수있다.
새로운 연결들은 uIP가 uip_connect()함수를 호출함으로서 연결된다. 이 함수는 새로운 연결을 할당하고 연결상태 플래그를 세팅한다. ip주소나 포트등을 저장해서 다음 연결시에는 uIP에 의해 검사된다. uip_connect()함수는 uip_conn구조체를 리턴하는데 만약 여유있는 연결슬롯이 없다면 NULL을 리턴한다.
The function uip_ipaddr() may be used to pack an IP address into the two element 16-bit array used by uIP to represent IP addresses.
Two examples of usage are shown below. The first example shows how to open a connection to TCP port 8080 of the remote end of the current connection. If there are not enough TCP connection slots to allow a new connection to be opened, the uip_connect() function returns NULL and the current connection is aborted by uip_abort().
uIP_connect()함수는 IP주소를 표현하기위해 uip_ipaddr()함수를 사용하는데 16비트 크기의 두개의 엘리먼트로 구성된 배열에 담아 표현한다. 다음 두가지 예제를 살펴보자. 첫번째 예제는 새로운 연결이 TCP 포트 8080에 할당 되는 예제이다. 만약 TCP연결 슬롯에 여유공간이 없다면 uip_connect()함수는 NULL을 리턴하고 uip_abort()함수로 연결을 해지할 것이다.
void connect_example1_app(void) { if(uip_connect(uip_conn->ripaddr, HTONS(8080)) == NULL) { uip_abort(); } }
The second example shows how to open a new connection to a specific IP address. No error checks are made in this example.
두번째 예제는 IP를 지정하는 예제이다. 이 예제에서는 에러체크를 하지않는다.
void connect_example2(void) { u16_t ipaddr[2]; uip_ipaddr(ipaddr, 192,168,0,1); uip_connect(ipaddr, HTONS(8080)); }
네트워크 디바이스 드라이버의 관점에서 본다면 uIP는 uip_input()함수와 uip_periodic()함수로 구성된다. uip_input()함수는 IP패킷을 받아 uip_buf 패킷버퍼에 넣을때 디바이스 드라이버에 의해 호출된다. 이 함수는 패킷을 처리하고 그 데이터를 리턴한다. (uip_len변수가 넌제로면 패킷을 처리해서 전송할수있는 패킷임을 말한다.) 디바이스 드라이버는 uip_input()이 리턴한 데이터를 네트워크로 내보낸다.
The uip_periodic() function should be invoked periodically once per connection by the device driver, typically one per second. This function is used by uIP to drive protocol timers and retransmissions, and when it returns it may have placed an outbound packet in the uip_buf buffer.
uip_periodic()함수는 디바이스 드라이버에 의해 주기적으로 호출되는데 주로 일초에 한번 호출된다. 이 함수는 uIP가 프로토콜을 타이머와 재전송작업을 컨트롤 할때 사용하는 함수이다. 그리고 uip_periodic()함수가 리턴 할 때는 uip_buf에 밖으로 나갈수있는 패킷(outbound packet)이 만들어져 있을 것이다.
uIP를 사용하는 아키텍쳐는 uIP의 몇가지 기능들을 자세히 구현해야한다. 이 작업은 손이 많이가는 작업이지만 uIP배포본에서 C로 구현한 코드를 얻을 수있다.
TCP와 IP프로토콜은 각각의 헤더부분에 체크섬 필드를 두어 체크섬을 수행하는데 이런 체크섬 계산은 패킷을 보낼때와 받을때 매번 계산되어진다. uIP스택이 돌고있는 아키텍쳐도 체크섬계산이 필요한데 체크섬 계산을 얼마나 효율적으로 하느냐가 중요하다.
Because of this, uIP does not implement a generic checksum function, but leaves this to the architecture specific files which must implement the two functions uip_ipchksum() and uip_tcpchksum(). The checksum calculations in those functions can be written in highly optimized assembler rather than generic C code.
An example C implementation of the checksum function is provided in the uIP distribution.
이렇기 때문에 uIP는 일반적인 체크섬 함수를 쓰지않는다. 하지만 uip_ipchksum()함수와 uip_tcpchksum()함수를 사용해서 체크섬을 구현할수있다. 이 두 함수들은 어셈블리어로 구현되어있다. C로 구현된 체크섬 예제가 uIP 배포판에 제공된다.
TCP프로토콜은 32비트 연산을 한다. 하지만 uIP를 쓰는 대부분의 시스템은 32비트 연산을 하지않는다. uIP는 32비트 연산을 main 코드에서 하지않고 특정 모듈을 통해서 구현된다. 그 특정 모듈은 uip_add32()함수를 구현해야 한다. 이 함수는 전역변수 uip_acc32에 32비트 연산의 결과를 저장한다.
이 섹션에서는 아주 간단한 uIP예제를 설명한다. uIP배포판에는 좀더 자세하고 복잡한 어플리케이션들이 제공된다.
첫번째 예제는 아주 간단한 예제입니다. 어플리케이션이 1234포트로 리스닝을 한다. 연결이 되면 어플리케이션은 응답으로 "ok"를 전송한다.
The implementation of this application is shown below. The application is initialized with the function called example1_init() and the uIP callback function is called example1_app(). For this application, the configuration variable UIP_APPCALL should be defined to be example1_app().
밑의 소스에서처럼 어플리케이션은 example1_init()로 초기화하고 example1_app()콜백함수를 호출한다. 설정변수인 UIP_APPCALL에 example1_app()가 연결 되야 한다.
void example1_init(void) { uip_listen(HTONS(1234)); } void example1_app(void) { if(uip_newdata() || uip_rexmit()) { uip_send("ok\n", 3); } }
The initialization function calls the uIP function uip_listen() to register a listening port. The actual application function example1_app() uses the test functions uip_newdata() and uip_rexmit() to determine why it was called. If the application was called because the remote end has sent it data, it responds with an "ok". If the application function was called because data was lost in the network and has to be retransmitted, it also sends an "ok". Note that this example actually shows a complete uIP application. It is not required for an application to deal with all types of events such as uip_connected() or uip_timedout().
초기화 함수는 리스닝 포트를 등록하기 위해서 uIP함수 uip_listen()을 호출한다. 실제 어플리케이션 함수 example1_app()는 uip_newdata()와 uip_rexmit()를 테스트한다. 새로운 데이터를 받은경우,네트워크상에서 패킷이 분실되 재전송 요청인 경우에 "ok"를 보낸다. 이 예제에는 어플리케이션의 틀만 보여줄 뿐 uip_connected()나 uip_timedout()과 같은 이벤트들의 모든 타입들은 다루지 않는다.
두번째 예제에서는 앞서 살펴본 예제보다 좀더 진보된 예제를 살펴본다. uip_conn구조체를 사용해서 각 필드들을 살펴 볼 것이다.
This application is similar to the first application in that it listens to a port for incoming connections and responds to data sent to it with a single "ok". The big difference is that this application prints out a welcoming "Welcome!" message when the connection has been established.
이 어플리케이션은 리스닝 포트를 열어 연결을 기다리고 데이터를 받으면 "ok"로 응답 메시지를 날려주는데서 비슷하지만, 진보시켜서 연결시에 "Welcome!"이란 메시지를 찍을 것이다.
This seemingly small change of operation makes a big difference in how the application is implemented. The reason for the increase in complexity is that if data should be lost in the network, the application must know what data to retransmit. If the "Welcome!" message was lost, the application must retransmit the welcome and if one of the "ok" messages is lost, the application must send a new "ok".
앞의 예제에 비해 기능상의 차이는 별로 없지만 어플리케이션의 구현코드는 많이 다르다. 왜냐 하면 네트워크상에서 손실된 데이터를 처리해주기 위한 재전송 루틴이 추가되기 때문이다. 만약 "welcome!"메시지가 유실된다면 어플리케이션은 "welcome!" 메시지를 재전송해야하고, "ok"메시지가 유실되면 어플리케이션은 새로운 "ok" 메시지를 다시만들어 전송해야 한다.
The application knows that as long as the "Welcome!" message has not been acknowledged by the remote host, it might have been dropped in the network. But once the remote host has sent an acknowledgment back, the application can be sure that the welcome has been received and knows that any lost data must be an "ok" message. Thus the application can be in either of two states: either in the WELCOME-SENT state where the "Welcome!" has been sent but not acknowledged, or in the WELCOME-ACKED state where the "Welcome!" has been acknowledged.
어플리케이션은 "welcome!"메시지에 대한 상대편 호스트의 응답이 없다면 네트워크상에서 패킷이 유실되었다고 판단한다. 그러나 상대편 호스트에서 응답메시지를 주면, 어플리케이션은 웰컴 메시지의 응답인지 재전송한 "ok"메시지의 응답인지를 판단해야 한다. 그래서 어플리케이션은 두가지 상태를 가질수 있다. : "welcome!"메시지를 전송해놓고 응답메지시를 받지 못한경(WELCOME-SENT)우, "Welcome!"메시지를 보내고 확인메시지를 받은 경우(WELCOME-ACKED).
When a remote host connects to the application, the application sends the "Welcome!" message and sets it's state to WELCOME-SENT. When the welcome message is acknowledged, the application moves to the WELCOME-ACKED state. If the application receives any new data from the remote host, it responds by sending an "ok" back.
원격지 호스트가 어플리케이션에 연결을 시도할때 어플리케이션은 "welcome!"메시지를 보내고 상태를 WELCOME-SENT로 세팅한다. 그후에 응답메시지를 받았다면 어플리케이션의 상태는 WELCOME-ACKED상태로 바뀌게 된다. 만약 어플리케이션이 원격지 호스트로 부터 아무 메시지도 받지 못했다면 재전송루틴에 의해 "ok"메시지가 전송된다. 만약 어플리케이션에게 재전송을 요청한다면, 어플리케이션은 상태를 확인한후 WELCOME-SENT다면 "welcome!"메시지를 전송하고 "WELCOME-ACKED"상태이면 "ok"메시지를 전송한다.
If the application is requested to retransmit the last message, it looks at in which state the application is. If the application is in the WELCOME-SENT state, it sends a "Welcome!" message since it knows that the previous welcome message hasn't been acknowledged. If the application is in the WELCOME-ACKED state, it knows that the last message was an "ok" message and sends such a message.
어플리케이션이 마지막 메시지에 대해 재전송요청을 받았다면, 제일먼저 어플리케이션의 상태를 살펴본다. WELCOME-SENT상태면 웰컴 메시지에 대한 ACK가 없는 상태이므로 "welcome!"메시지를 전송하고, WELCOME-ACKED상태면 "ok"메시지를 전송한다.
The implementation of this application is seen below. This configuration settings for the application is follows after its implementation.
struct example2_state { enum {WELCOME_SENT, WELCOME_ACKED} state; }; void example2_init(void) { uip_listen(HTONS(2345)); } void example2_app(void) { struct example2_state *s; s = (struct example2_state *)uip_conn->appstate; if(uip_connected()) { s->state = WELCOME_SENT; uip_send("Welcome!\n", 9); return; } if(uip_acked() && s->state == WELCOME_SENT) { s->state = WELCOME_ACKED; } if(uip_newdata()) { uip_send("ok\n", 3); } if(uip_rexmit()) { switch(s->state) { case WELCOME_SENT: uip_send("Welcome!\n", 9); break; case WELCOME_ACKED: uip_send("ok\n", 3); break; } } }
The configuration for the application:
#define UIP_APPCALL example2_app #define UIP_APPSTATE_SIZE sizeof(struct example2_state)
만약 하나의 어플리케이션 안에 여러개의 포트가 열려 다중기능을 수행해야하는 경우는 밑의 소스처럼 연결별로 포트들을 지정해주어야 한다.
void example3_init(void) { example1_init(); example2_init(); } void example3_app(void) { switch(uip_conn->lport) { case HTONS(1234): example1_app(); break; case HTONS(2345): example2_app(); break; } }
이 예제는 수행속도가 느린 디바이스들과의 연동에서 uIP가 어떻게 컨트롤 하는지를 보여준다. 예를 들면, 웹페이지를 긁어서 파일저장할때 저장하는 동안에 새로운 데이터를 이어서 파일에 저장해야하는 경우.
void example4_init(void) { u16_t ipaddr[2]; uip_ipaddr(ipaddr, 192,168,0,1); uip_connect(ipaddr, HTONS(80)); } void example4_app(void) { if(uip_connected() || uip_rexmit()) { uip_send("GET /file HTTP/1.0\r\nServer:192.186.0.1\r\n\r\n", 48); return; } if(uip_newdata()) { device_enqueue(uip_appdata, uip_datalen()); if(device_queue_full()) { uip_stop(); } } if(uip_poll() && uip_stopped()) { if(!device_queue_full()) { uip_restart(); } } }
When the connection has been established, an HTTP request is sent to the server. Since this is the only data that is sent, the application knows that if it needs to retransmit any data, it is that request that should be retransmitted. It is therefore possible to combine these two events as is done in the example.
연결 완료되면, 서버에게 HTTP요청을 보낸다.
When the application receives new data from the remote host, it sends this data to the device by using the function device_enqueue(). It is important to note that this example assumes that this function copies the data into its own buffers. The data in the uip_appdata buffer will be overwritten by the next incoming packet.
원격지 호스트로부터 데이터를 받았을때, 이 데이터는 device_enqueue()함수를 통해 디바이스에게 전달된다. 중요한것은 디바이스 내부 버퍼에 카피해간다는 사실, 따라서 현재의 패킷은 다음에 들어오는 패킷에 의해 덮어쓰여진다.
If the device's queue is full, the application stops the data from the remote host by calling the uIP function uip_stop(). The application can then be sure that it will not receive any new data until uip_restart() is called. The application polling event is used to check if the device's queue is no longer full and if so, the data flow is restarted with uip_restart().
만약 디바이스의 큐가 가득 차있다면, 어플리케이션은 uip_stop()함수를 통해 원격지로부터 데이타를 받는 일을 중지한다. 그리고 uip_restart()함수가 호출될때까지 어플리케이션은 어떤 데이터도 받지 않는다. 어플리케이션은 디바이스 큐를 계속 검사하고 있다가, 여유가 생기면 바로 uip_restart()함수를 호출한다.
이 예제는 아주 간단한 파일 서버 어플리케이션이다. 두개의 포트를 열고서 두개의 파일을 보내는데 어느 파일을 보낼지 결정하는 기능이다. 만약 파일 형식이 맞다면 이 예제는 웹서버로 동작할 수있다.
struct example5_state { char *dataptr; unsigned int dataleft; }; void example5_init(void) { uip_listen(HTONS(80)); uip_listen(HTONS(81)); } void example5_app(void) { struct example5_state *s; s = (struct example5_state)uip_conn->appstate; if(uip_connected()) { switch(uip_conn->lport) { case HTONS(80): s->dataptr = data_port_80; s->dataleft = datalen_port_80; break; case HTONS(81): s->dataptr = data_port_81; s->dataleft = datalen_port_81; break; } uip_send(s->dataptr, s->dataleft); return; } if(uip_acked()) { if(s->dataleft < uip_mss()) { uip_close(); return; } s->dataptr += uip_conn->len; s->dataleft -= uip_conn->len; uip_send(s->dataptr, s->dataleft); } }
The application state consists of a pointer to the data that should be sent and the size of the data that is left to send. When a remote host connects to the application, the local port number is used to determine which file to send. The first chunk of data is sent using uip_send(). uIP makes sure that no more than MSS bytes of data is actually sent, even though s->dataleft may be larger than the MSS.
어플리케이션 상태는 두가지 포인터로 구성된다. 보낼 데이터의 포인터와, 앞으로 보낼 데이터의 크기. 원격지 호스트가 어플리케이션에 연결될때 로컬 포트번호는 어느 파일을 보낼지 결정한다. uip_send()함수로 첫번째 데이터 chunk를 전송한다. uIP는 전송할 데이터크기가 MSS를 넘지 않게 보장해 줘야 한다.
The application is driven by incoming acknowledgments. When data has been acknowledged, new data can be sent. If there is no more data to send, the connection is closed using uip_close().
어플리케이션은 확인메시지를 받고 그것에 따라 동작한다. 이전에 보낸 데이터에 대한 ACK메시지를 받았다면 새로운 데이터를 전송한다. 보낼 데이터가 더이상 없다면 연결은 uip_close()에 의해 종료된다.
uIP를 사용해서 큰 프로그램을 작설할때는 구조화된 방법으로 uIP API를 사용할 수있다. 앞으로 보여줄 예제는 위에서 보여줬던 예제보다 더 큰 프로토콜을 구현할 때 유용하게 사용되는 구조화된 방법을 소개한다. 이 프로그램은 uIP 이벤트 핸들러에 의해 동작한다. 총 7가지의 핸들러가 호출 된다. newdata(), acked(), senddata(), connected(), closed(), aborted(), timedout().
The uIP event handler function is shown below.
void example6_app(void) { if(uip_aborted()) { aborted(); } if(uip_timedout()) { timedout(); } if(uip_closed()) { closed(); } if(uip_connected()) { connected(); } if(uip_acked()) { acked(); } if(uip_newdata()) { newdata(); } if(uip_rexmit() || uip_newdata() || uip_acked() || uip_connected() || uip_poll()) { senddata(); } }
The function starts with dealing with any error conditions that might have happened by checking if uip_aborted() or uip_timedout() are true. If so, the appropriate error function is called. Also, if the connection has been closed, the closed() function is called to the it deal with the event.
uip_aborted()나 uip_timedout()함수가 true이면 에러 함수를 호출하고, 연결을 해제한다. closed()함수는 uip_closed()함수가 참이면 실행된다.
Next, the function checks if the connection has just been established by checking if uip_connected() is true. The connected() function is called and is supposed to do whatever needs to be done when the connection is established, such as intializing the application state for the connection. Since it may be the case that data should be sent out, the senddata() function is called to deal with the outgoing data.
다음은, uip_connected()을 체크함으로서 연결 여부를 확인 한다. 연결이 되었다면 connected()함수를 호출해서 연결 설정 및 초기화 과정을 거친다. 그리고 데이터를 전송해야되는 경우에는 senddata()함수를 사용해서 밖으로 전송한다.
The following very simple application serves as an example of how the application handler functions might look. This application simply waits for any data to arrive on the connection, and responds to the data by sending out the message "Hello world!". To illustrate how to develop an application state machine, this message is sent in two parts, first the "Hello" part and then the "world!" part.
밑의 예제는 어플리케이션의 헨들러함수들이 어떻게 동작하는지 보여주는 예제이다. 이 어플리케이션은 연결을 기다리다가 연결요청 메시지가 오면 "Hello world!"메시지를 보낼것이다. 어플리케이션 상태에 따라 어떻게 동작되는지 보여주기 위해 메시지를 두 부분으로 나누어서 전송했다. "hello"부분과 "world!".
#define STATE_WAITING 0 #define STATE_HELLO 1 #define STATE_WORLD 2 struct example6_state { u8_t state; char *textptr; int textlen; }; static void aborted(void) {} static void timedout(void) {} static void closed(void) {} static void connected(void) { struct example6_state *s = (struct example6_state *)uip_conn->appstate; s->state = STATE_WAITING; s->textlen = 0; } static void newdata(void) { struct example6_state *s = (struct example6_state *)uip_conn->appstate; if(s->state == STATE_WAITING) { s->state = STATE_HELLO; s->textptr = "Hello "; s->textlen = 6; } } static void acked(void) { struct example6_state *s = (struct example6_state *)uip_conn->appstate; s->textlen -= uip_conn->len; s->textptr += uip_conn->len; if(s->textlen == 0) { switch(s->state) { case STATE_HELLO: s->state = STATE_WORLD; s->textptr = "world!\n"; s->textlen = 7; break; case STATE_WORLD: uip_close(); break; } } } static void senddata(void) { struct example6_state *s = (struct example6_state *)uip_conn->appstate; if(s->textlen > 0) { uip_send(s->textptr, s->textlen); } }
The application state consists of a "state" variable, a "textptr" pointer to a text message and the "textlen" length of the text message. The "state" variable can be either "STATE_WAITING", meaning that the application is waiting for data to arrive from the network, "STATE_HELLO", in which the application is sending the "Hello" part of the message, or "STATE_WORLD", in which the application is sending the "world!" message.
어플리케이션의 상태는 "state변수와 "textptr"텍스트포인터와 "textlen"텍스트메시지의 길이로 구성된다. "state"변수는 연결이 된후 데이터를 기다리는 상태인 "STATE_WAITING", 어플리케이션이 "helo"부분을 전송한 "STATE_HELLO"상태, "world!"메시지를 전송 하고있는 "STATE_WORDL"상태가 있다.
The application does not handle errors or connection closing events, and therefore the aborted(), timedout() and closed() functions are implemented as empty functions.
어플리케이션은 aborted(), timedout(), closed() 함수에 의한 에러핸들링이나 연결해제를 하지않는다. 그 함수들은 구현부가 비어있다.
The connected() function will be called when a connection has been established, and in this case sets the "state" variable to be "STATE_WAITING" and the "textlen" variable to be zero, indicating that there is no message to be sent out.
connected()함수는 연결 설정될때 호출되고 상태변수를 "STATE_WATING","textlen"을 0으로 초기화 한다.
When new data arrives from the network, the newdata() function will be called by the event handler function. The newdata() function will check if the connection is in the "STATE_WAITING" state, and if so switches to the "STATE_HELLO" state and registers a 6 byte long "Hello " message with the connection. This message will later be sent out by the senddata() function.
네트워크로 부터 새로운 데이터가 도착하면 이벤트 헨들러는 newdata()함수를 호출한다. 이 함수는 "STATE_WAITING"상태면 어플리케이션은 지금 도착한 상대로부터 데이터를 기다리고 있는중이라는 의미인 "STATE_HELLO"로 상태를 바꾸고, 6바이트의 "hello"파트를 저장한다. 이 메시지는 senddata()에 의해서 나중에 네트워크로 보내질 것이다.
The acked() function is called whenever data that previously was sent has been acknowleged by the receiving host. This acked() function first reduces the amount of data that is left to send, by subtracting the length of the previously sent data (obtained from "uip_conn->len") from the "textlen" variable, and also adjusts the "textptr" pointer accordingly. It then checks if the "textlen" variable now is zero, which indicates that all data now has been successfully received, and if so changes application state. If the application was in the "STATE_HELLO" state, it switches state to "STATE_WORLD" and sets up a 7 byte "world!\n" message to be sent. If the application was in the "STATE_WORLD" state, it closes the connection.
acked()함수는 데이터를 보낼때 마다 상대편 호스트로 부터 호출된다. 이 함수는 보낼 데이터크기에서 보낸 데이터 크기를 빼주고 다음 전송할 부분을 "textptr"에 지정한다. 만약 "textlen"변수가 0이면, 지금 모든 데이터는 잘 받았다는 것을 말하므로 어플리케이션의 상태를 "STATE_WORLD"로 바꾸고 7바이트메시지 "world\n"를 보낸다. 반면 어플리케이션의 상태가 "STATE_WORLD"였다면, 연결을 해제한다.
Finally, the senddata() function takes care of actually sending the data that is to be sent. It is called by the event handler function when new data has been received, when data has been acknowledged, when a new connection has been established, when the connection is polled because of inactivity, or when a retransmission should be made. The purpose of the senddata() function is to optionally format the data that is to be sent, and to call the uip_send() function to actually send out the data. In this particular example, the function simply calls uip_send() with the appropriate arguments if data is to be sent, after checking if data should be sent out or not as indicated by the "textlen" variable.
마지막으로 senddata() 함수는 데이터를 네트워크 상에 내보내는 함수이다. 이 함수는 새로운 데이터를 받았을때, ACK메시지를 상태일때,새로운 연결이 요청 ?을때, 재전송 할때의 경우에 이벤트 핸들러에 의해서 호출된다. senddata()함수의 목적은 보낼 데이터의 부가적인 옵션을 세팅하는데 있다. 보낼 데이터의 정보를 저장한 후 uip_send()를 호출해서 데이터를 밖으로 내보낸다. 실제예에서 이 함수는 uip_send() 함수를 호출하기전에 "textlen" 변수로 데이터를 보낼지말지를 간단하게 테스트한다.
It is important to note that the senddata() function never should affect the application state; this should only be done in the acked() and newdata() functions.
senddata() 함수는 어플리케이션 상태를 변경하거나 영향을 주지 않는다. 이미 acked()나 newdata() 함수에서 변경했다.
1.3.3