background preloader

Communication

Facebook Twitter

S Guide to Network Programming. S Guide to Network Programming. Using Internet Sockets Brian "Beej Jorgensen" Hall beej@beej.us Version 3.0.15 July 3, 2012 Copyright © 2012 Brian "Beej Jorgensen" Hall Contents 1. 1.1. 1.2. 1.3. 1.4. 1.5. 1.6. 1.7. 1.8. 1.9. 2. 2.1. 2.2. 3. 3.1. 3.2. 3.3. s 3.4. 4. 5.1. getaddrinfo()—Prepare to launch! 5.2. socket()—Get the File Descriptor! 5.3. bind()—What port am I on? 5.4. connect()—Hey, you! 5.5. listen()—Will somebody please call me? 5.6. accept()—"Thank you for calling port 3490. " 5.7. send() and recv()—Talk to me, baby! 5.8. sendto() and recvfrom()—Talk to me, DGRAM-style 5.9. close() and shutdown()—Get outta my face! 5.10. getpeername()—Who are you? 5.11. gethostname()—Who am I? 6. 6.1. 6.2. 6.3. 7. 7.1. 7.2. select()—Synchronous I/O Multiplexing 7.3. 7.4. 7.5. 7.6. 8. 9.1. accept() 9.2. bind() 9.3. connect() 9.4. close() 9.5. getaddrinfo(), freeaddrinfo(), gai_strerror() 9.6. gethostname() 9.7. gethostbyname(), gethostbyaddr() 9.8. getnameinfo() 9.9. getpeername() 9.10. errno 9.11. fcntl() 9.12. htons(), htonl(), ntohs(), ntohl() 10.

Handle multiple socket connections with fd_set and select on Linux | Binary Tides. #include <stdio.h> #include <string.h> //strlen #include <stdlib.h> #include <errno.h> #include <unistd.h> //close #include <arpa/inet.h> //close #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <sys/time.h> //FD_SET, FD_ISSET, FD_ZERO macros #define TRUE 1 #define FALSE 0 #define PORT 8888 int main(int argc , char *argv[]) int opt = TRUE; int master_socket , addrlen , new_socket , client_socket[30] , max_clients = 30 , activity, i , valread , sd; int max_sd; struct sockaddr_in address; char buffer[1025]; fd_set readfds; char *message = "ECHO Daemon v1.0 \r\n"; for (i = 0; i < max_clients; i++) client_socket[i] = 0; if( (master_socket = socket(AF_INET , SOCK_STREAM , 0)) == 0) perror("socket failed"); exit(EXIT_FAILURE); if( setsockopt(master_socket, SOL_SOCKET, SO_REUSEADDR, (char *)&opt, sizeof(opt)) < 0 ) perror("setsockopt"); address.sin_family = AF_INET; address.sin_addr.s_addr = INADDR_ANY; address.sin_port = htons( PORT ); perror("bind failed"); if (listen(master_socket, 3) < 0)

The World of select() So just why am I so hyped on select()? One traditional way to write network servers is to have the main server block on accept(), waiting for a connection. Once a connection comes in, the server fork()s, the child process handles the connection and the main server is able to service new incoming requests. With select(), instead of having a process for each request, there is usually only one process that "multi-plexes" all requests, servicing each request as much as it can. So one main advantage of using select() is that your server will only require a single process to handle all requests. One major disadvantage of using select(), is that your server cannot act like there's only one client, like with a fork()'ing solution. Okay, so how do you use select()? Select() works by blocking until something happens on a file descriptor (aka a socket). Most select()-based servers look pretty much the same: Fill up a fd_set structure with the file descriptors you want to know when data comes in on.

Introduction to non-blocking I/O. Programs that use non-blocking I/O tend to follow the rule that every function has to return immediately, i.e. all the functions in such programs are nonblocking. Thus control passes very quickly from one routine to the next. You have to understand the overall picture to some extent before any one piece makes sense. (This makes it harder to get your mind around than the same program written with blocking calls, but the benefits mentioned elsewhere in this document make up for this trouble, so don't be discouraged.) Many objects need to wait for time to pass or for an external event to occur, but because their methods must return immediately, they can't do the obvious or natural thing.

Instead, they use the "state machine" technique. To illustrate this, let's consider a simple networking class that lets you send a file to a remote machine, assuming the connection is all set up. See also: Copyright Dan Kegel 1999. IEEE 802.11. IEEE 802.11 is a set of media access control (MAC) and physical layer (PHY) specifications for implementing wireless local area network (WLAN) computer communication in the 2.4, 3.6, 5 and 60 GHz frequency bands. They are created and maintained by the IEEE LAN/MAN Standards Committee (IEEE 802). The base version of the standard was released in 1997 and has had subsequent amendments. The standard and amendments provide the basis for wireless network products using the Wi-Fi brand. While each amendment is officially revoked when it is incorporated in the latest version of the standard, the corporate world tends to market to the revisions because they concisely denote capabilities of their products.

As a result, in the market place, each revision tends to become its own standard. The LinksysWRT54G contains a router with an 802.11b/g radio and two antennae General description[edit] History[edit] 802.11 technology has its origins in a 1985 ruling by the U.S. Protocol[edit] 802.11b[edit] DHCP. DHCP является расширением протокола BOOTP, использовавшегося ранее для обеспечения бездисковых рабочих станций IP-адресами при их загрузке. DHCP сохраняет обратную совместимость с BOOTP. История[править | править исходный текст] Стандарт протокола DHCP был принят в октябре 1993 года. Действующая версия протокола (март 1997 года) описана в RFC 2131. Новая версия DHCP, предназначенная для использования в среде IPv6, носит название DHCPv6 и определена в RFC 3315 (июль 2003 года).

Распределение IP-адресов[править | править исходный текст] Протокол DHCP предоставляет три способа распределения IP-адресов: Некоторые реализации службы DHCP способны автоматически обновлять записи DNS, соответствующие клиентским компьютерам, при выделении им новых адресов. Опции DHCP[править | править исходный текст] Помимо IP-адреса, DHCP также может сообщать клиенту дополнительные параметры, необходимые для нормальной работы в сети. Некоторыми из наиболее часто используемых опций являются: Time to live. IP packets[edit] DNS records[edit] TTLs also occur in the Domain Name System (DNS), where they are set by an authoritative name server for a particular resource record.

When a caching (recursive) nameserver queries the authoritative nameserver for a resource record, it will cache that record for the time (in seconds) specified by the TTL. If a stub resolver queries the caching nameserver for the same record before the TTL has expired, the caching server will simply reply with the already cached resource record rather than retrieve it from the authoritative nameserver again. Nameservers may also have a TTL set for NXDOMAIN (acknowledgment that a domain does not exist); but they are generally short in duration (three hours at most). The units used are seconds. An older common TTL value for DNS was 86400 seconds, which is 24 hours.

Newer DNS methods that are part of a DR (Disaster Recovery) system may have some records deliberately set extremely low on TTL. HTTP[edit] See also[edit] Network interface controller. "Network card" redirects here. For the British Rail discount card, see Network Railcard. A network interface controller (NIC, also known as a network interface card, network adapter, LAN adapter, Physical Network Interface[1] and by similar terms) is a computer hardware component that connects a computer to a computer network.[2] Early network interface controllers were commonly implemented on expansion cards that plugged into a computer bus.

The low cost and ubiquity of the Ethernet standard means that most newer computers have a network interface built into the motherboard. Purpose[edit] The network controller implements the electronic circuitry required to communicate using a specific physical layer and data link layer standard such as Ethernet, Fibre Channel, Wi-Fi or Token Ring. Although other network technologies exist, IEEE 802 networks including the Ethernet variants have achieved near-ubiquity since the mid-1990s. Implementation[edit] An ATM network interface. See also[edit] NAT. Функционирование[править | править исходный текст] Принимая пакет от локального компьютера, роутер смотрит на IP-адрес назначения. Если это локальный адрес, то пакет пересылается другому локальному компьютеру. Если нет, то пакет надо переслать наружу в интернет. Но ведь обратным адресом в пакете указан локальный адрес компьютера, который из интернета будет недоступен.

Поэтому роутер «на лету» транслирует (подменяет) обратный IP-адрес пакета на свой внешний (видимый из интернета) IP-адрес и меняет номер порта (чтобы различать ответные пакеты, адресованные разным локальным компьютерам). Комбинацию, нужную для обратной подстановки, роутер сохраняет у себя во временной таблице. Статический NAT — Отображение незарегистрированного IP-адреса на зарегистрированный IP-адрес на основании один к одному.

Динамический NAT — Отображает незарегистрированный IP-адрес на зарегистрированный адрес от группы зарегистрированных IP-адресов. Механизм NAT определён в RFC 1631, RFC 3022. Старые протоколы. NAT. IPv6. IPv6 (англ. Internet Protocol version 6) — новая версия протокола IP, призванная решить проблемы, с которыми столкнулась предыдущая версия (IPv4) при её использовании в интернете, за счёт использования длины адреса 128 бит вместо 32. Протокол был разработан IETF. В настоящее время протокол IPv6 уже используется в нескольких тысячах сетей по всему миру (более 14000 сетей на осень 2013), но пока ещё не получил столь широкого распространения в Интернете, как IPv4. На конец 2012 года, доля IPv6 сетевого трафика составляла около 1%[1].

После того, как адресное пространство в IPv4 закончится, два стека протоколов — IPv6 и IPv4 — будут использоваться параллельно (англ. dual stack), с постепенным увеличением доли трафика IPv6 по сравнению с IPv4. История создания[править | править исходный текст] В конце 1980-х стала очевидна необходимость разработки способов сохранения адресного пространства Интернета.

Исчерпание IPv4 адресов в 2012 году[править | править исходный текст] Глобальные Link-Local. IPv4. Internet Protocol version 4 (IPv4) is the fourth version in the development of the Internet Protocol (IP) Internet, and routes most traffic on the Internet.[1] However, a successor protocol, IPv6, has been defined and is in various stages of production deployment. IPv4 is described in IETF publication RFC 791 (September 1981), replacing an earlier definition (RFC 760, January 1980). IPv4 is a connectionless protocol for use on packet-switched networks. It operates on a best effort delivery model, in that it does not guarantee delivery, nor does it assure proper sequencing or avoidance of duplicate delivery. These aspects, including data integrity, are addressed by an upper layer transport protocol, such as the Transmission Control Protocol (TCP). Addressing [edit] Decomposition of the quad-dotted IPv4 address representation to its binary value IPv4 uses 32-bit (four-byte) addresses, which limits the address space to 4294967296 (232) addresses.

Address representations[edit] Allocation[edit] Port (computer networking) In computer networking, a port is a software construct serving as a communications endpoint in a computer's host operating system. A port is always associated with an IP address of a host and the protocol type of the communication. It completes the destination or origination address of a communications session. A port is identified for each address and protocol by a 16-bit number, commonly known as the port number. Specific, well-known port numbers are often used to identify specific applications and services. In the client-server model of application architecture, ports are used to provide a multiplexing service on each port number that network clients connect to for service initiation, after which communication is reestablished on another connection-specific port number.

Transport Layer protocols, such as the Transmission Control Protocol (TCP) and the User Datagram Protocol (UDP), specify a source and destination port number in their packet headers. Examples include: