Berkeley sockets is an application programming interface (API) for Internet sockets and Unix domain sockets, used for inter-process communication (IPC). It is commonly implemented as a library of linkable modules. It originated with the 4.2BSD Unix operating system, which was released in 1983.
A socket is an abstract representation (handle) for the local endpoint of a network communication path. The Berkeley sockets API represents it as a file descriptor (file handle) in the Unix philosophy that provides a common interface for input and output to streams of data.
Berkeley sockets evolved with little modification from a de facto standard into a component of the POSIX specification. The term POSIX sockets is essentially synonymous with Berkeley sockets, but they are also known as BSD sockets, acknowledging the first implementation in the Berkeley Software Distribution.
Berkeley sockets originated with the 4.2BSD Unix operating system, released in 1983, as a programming interface. Not until 1989, however, could the University of California, Berkeley release versions of the operating system and networking library free from the licensing constraints of AT&T Corporation's proprietary Unix.
All modern operating systems implement a version of the Berkeley socket interface. It became the standard interface for applications running in the Internet. Even the Winsock implementation for MS Windows, created by unaffiliated developers, closely follows the standard.
The BSD sockets API is written in the C programming language. Most other programming languages provide similar interfaces, typically written as a wrapper library based on the C API.[1]
As the Berkeley socket API evolved and ultimately yielded the POSIX socket API,[2] certain functions were deprecated or removed and replaced by others. The POSIX API is also designed to be reentrant and supports IPv6.
The STREAMS-based Transport Layer Interface (TLI) API offers an alternative to the socket API. Many systems that provide the TLI API also provide the Berkeley socket API.
Non-Unix systems often expose the Berkeley socket API with a translation layer to a native networking API. Plan 9[3] and Genode[4] use file-system APIs with control files rather than file-descriptors.
The Berkeley socket interface is defined in several header files. The names and content of these files differ slightly between implementations. In general, they include:
The Berkeley socket API typically provides the following functions:
The function socket() creates an endpoint for communication and returns a file descriptor for the socket. It uses three arguments:
The function returns -1 if an error occurred. Otherwise, it returns an integer representing the newly assigned descriptor.
bind() associates a socket with an address. When a socket is created with socket(), it is only given a protocol family, but not assigned an address. This association must be performed before the socket can accept connections from other hosts. The function has three arguments:
bind() returns 0 on success and -1 if an error occurs.
After a socket has been associated with an address, listen() prepares it for incoming connections. However, this is only necessary for the stream-oriented (connection-oriented) data modes, i.e., for socket types (SOCK_STREAM, SOCK_SEQPACKET). listen() requires two arguments:
Once a connection is accepted, it is dequeued. On success, 0 is returned. If an error occurs, -1 is returned.
When an application is listening for stream-oriented connections from other hosts, it is notified of such events (cf. select() function) and must initialize the connection using function accept(). It creates a new socket for each connection and removes the connection from the listening queue. The function has the following arguments:
accept() returns the new socket descriptor for the accepted connection, or the value -1 if an error occurs. All further communication with the remote host now occurs via this new socket.
Datagram sockets do not require processing by accept() since the receiver may immediately respond to the request using the listening socket.
connect() establishes a direct communication link to a specific remote host identified by its address via a socket, identified by its file descriptor.
When using a connection-oriented protocol, this establishes a connection. Certain types of protocols are connectionless, most notably the User Datagram Protocol. When used with connectionless protocols, connect defines the remote address for sending and receiving data, allowing the use of functions such as send and recv. In these cases, the connect function prevents reception of datagrams from other sources.
connect() returns an integer representing the error code: 0 represents success, while –1 represents an error. Historically, in BSD-derived systems, the state of a socket descriptor is undefined if the call to connect fails (as it is specified in the Single Unix Specification), thus, portable applications should close the socket descriptor immediately and obtain a new descriptor with socket(), in the case the call to connect() fails.[5]
The functions gethostbyname() and gethostbyaddr() are used to resolve host names and addresses in the domain name system or the local host's other resolver mechanisms (e.g., /etc/hosts lookup). They return a pointer to an object of type struct hostent, which describes an Internet Protocol host. The functions use the following arguments:
The functions return a NULL pointer in case of error, in which case the external integer h_errno may be checked to see whether this is a temporary failure or an invalid or unknown host. Otherwise a valid struct hostent * is returned.
These functions are not strictly a component of the BSD socket API, but are often used in conjunction with the API functions for looking up a host. These functions are now considered legacy interfaces for querying the domain name system. New functions that are completely protocol-agnostic (supporting IPv6) have been defined. These new functions are getaddrinfo() and getnameinfo(), and are based on a new addrinfo data structure.[6]
This pair of functions appeared at the same time as the BSD socket API proper in 4.2BSD (1983),[7] the same year DNS was first created. Early versions did not query DNS and only performed /etc/hosts lookup. The 4.3BSD (1984) version added DNS in a crude way. The current implementation using Name Service Switch derives Solaris and later NetBSD 1.4 (1999).[8] Initially defined for NIS+, NSS makes DNS only one of the many options for lookup by these functions and its use can be disabled even today.[9]
The Berkeley socket API is a general interface for networking and interprocess communication, and supports the use of various network protocols and address architectures.
The following lists a sampling of protocol families (preceded by the standard symbolic identifier) defined in a modern Linux or BSD implementation:
A socket for communications is created with the socket() function, by specifying the desired protocol family (PF_-identifier) as an argument.
socket()
The original design concept of the socket interface distinguished between protocol types (families) and the specific address types that each may use. It was envisioned that a protocol family may have several address types. Address types were defined by additional symbolic constants, using the prefix AF instead of PF. The AF-identifiers are intended for all data structures that specifically deal with the address type and not the protocol family. However, this concept of separation of protocol and address type has not found implementation support and the AF-constants were defined by the corresponding protocol identifier, leaving the distinction between AF and PF constants as a technical argument of no practical consequence. Indeed, much confusion exists in the proper usage of both forms.[11]
The POSIX.1—2008 specification doesn't specify any PF-constants, but only AF-constants[12]
Raw sockets provide a simple interface that bypasses the processing by the host's TCP/IP stack. They permit implementation of networking protocols in user space and aid in debugging of the protocol stack.[13] Raw sockets are used by some services, such as ICMP, that operate at the Internet Layer of the TCP/IP model.
Berkeley sockets can operate in one of two modes: blocking or non-blocking.
A blocking socket does not return control until it has sent (or received) some or all data specified for the operation. It is normal for a blocking socket not to send all data. The application must check the return value to determine how many bytes have been sent or received and it must resend any data not already processed.[14] When using blocking sockets, special consideration should be given to accept() as it may still block after indicating readability if a client disconnects during the connection phase.
A non-blocking socket returns whatever is in the receive buffer and immediately continues. If not written correctly, programs using non-blocking sockets are particularly susceptible to race conditions due to variances in network link speed.[citation needed]
A socket is typically set to blocking or non-blocking mode using the functions fcntl and ioctl.
The operating system does not release the resources allocated to a socket until the socket is closed. This is especially important if the connect call fails and will be retried.
When an application closes a socket, only the interface to the socket is destroyed. It is the kernel's responsibility to destroy the socket internally. Sometimes, a socket may enter a TIME_WAIT state, on the server side, for up to 4 minutes.[15]
On SVR4 systems use of close() may discard data. The use of shutdown() or SO_LINGER may be required on these systems to guarantee delivery of all data.[16]
close()
shutdown()
The Transmission Control Protocol (TCP) is a connection-oriented protocol that provides a variety of error correction and performance features for transmission of byte streams. A process creates a TCP socket by calling the socket() function with the parameters for the protocol family (PF INET, PF_INET6), the socket mode for stream sockets (SOCK_STREAM), and the IP protocol identifier for TCP (IPPROTO_TCP).
Establishing a TCP server involves the following basic steps:
The following program creates a TCP server listening on port number 1100:
#include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> int main(void) { struct sockaddr_in sa; int SocketFD = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP); if (SocketFD == -1) { perror("cannot create socket"); exit(EXIT_FAILURE); } memset(&sa, 0, sizeof sa); sa.sin_family = AF_INET; sa.sin_port = htons(1100); sa.sin_addr.s_addr = htonl(INADDR_ANY); if (bind(SocketFD,(struct sockaddr *)&sa, sizeof sa) == -1) { perror("bind failed"); close(SocketFD); exit(EXIT_FAILURE); } if (listen(SocketFD, 10) == -1) { perror("listen failed"); close(SocketFD); exit(EXIT_FAILURE); } for (;;) { int ConnectFD = accept(SocketFD, NULL, NULL); if (ConnectFD == -1) { perror("accept failed"); close(SocketFD); exit(EXIT_FAILURE); } /* perform read write operations ... read(ConnectFD, buff, size) */ if (shutdown(ConnectFD, SHUT_RDWR) == -1) { perror("shutdown failed"); close(ConnectFD); close(SocketFD); exit(EXIT_FAILURE); } close(ConnectFD); } close(SocketFD); return EXIT_SUCCESS; }
Programming a TCP client application involves the following steps:
sockaddr_in
sin_family
sin_port
sin_addr
#include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> int main(void) { struct sockaddr_in sa; int res; int SocketFD; SocketFD = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP); if (SocketFD == -1) { perror("cannot create socket"); exit(EXIT_FAILURE); } memset(&sa, 0, sizeof sa); sa.sin_family = AF_INET; sa.sin_port = htons(1100); res = inet_pton(AF_INET, "192.168.1.3", &sa.sin_addr); if (connect(SocketFD, (struct sockaddr *)&sa, sizeof sa) == -1) { perror("connect failed"); close(SocketFD); exit(EXIT_FAILURE); } /* perform read write operations ... */ close(SocketFD); return EXIT_SUCCESS; }
The User Datagram Protocol (UDP) is a connectionless protocol with no guarantee of delivery. UDP packets may arrive out of order, multiple times, or not at all. Because of this minimal design, UDP has considerably less overhead than TCP. Being connectionless means that there is no concept of a stream or permanent connection between two hosts. Such data are referred to as datagrams (datagram sockets).
UDP address space, the space of UDP port numbers (in ISO terminology, the TSAPs), is completely disjoint from that of TCP ports.
An application may set up a UDP server on port number 7654 as follows. The programs contains an infinite loop that receives UDP datagrams with function recvfrom().
#include <stdio.h> #include <errno.h> #include <string.h> #include <sys/socket.h> #include <sys/types.h> #include <netinet/in.h> #include <unistd.h> /* for close() for socket */ #include <stdlib.h> int main(void) { int sock; struct sockaddr_in sa; char buffer[1024]; ssize_t recsize; socklen_t fromlen; memset(&sa, 0, sizeof sa); sa.sin_family = AF_INET; sa.sin_addr.s_addr = htonl(INADDR_ANY); sa.sin_port = htons(7654); fromlen = sizeof sa; sock = socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP); if (bind(sock, (struct sockaddr *)&sa, sizeof sa) == -1) { perror("error bind failed"); close(sock); exit(EXIT_FAILURE); } for (;;) { recsize = recvfrom(sock, (void*)buffer, sizeof buffer, 0, (struct sockaddr*)&sa, &fromlen); if (recsize < 0) { fprintf(stderr, "%s\n", strerror(errno)); exit(EXIT_FAILURE); } printf("recsize: %d\n ", (int)recsize); sleep(1); printf("datagram: %.*s\n", (int)recsize, buffer); } }
The following is a client program for sending a UDP packet containing the string "Hello World!" to address 127.0.0.1 at port number 7654.
#include <stdlib.h> #include <stdio.h> #include <errno.h> #include <string.h> #include <sys/socket.h> #include <sys/types.h> #include <netinet/in.h> #include <unistd.h> #include <arpa/inet.h> int main(void) { int sock; struct sockaddr_in sa; int bytes_sent; char buffer[200]; strcpy(buffer, "hello world!"); /* create an Internet, datagram, socket using UDP */ sock = socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP); if (sock == -1) { /* if socket failed to initialize, exit */ printf("Error Creating Socket"); exit(EXIT_FAILURE); } /* Zero out socket address */ memset(&sa, 0, sizeof sa); /* The address is IPv4 */ sa.sin_family = AF_INET; /* IPv4 addresses is a uint32_t, convert a string representation of the octets to the appropriate value */ sa.sin_addr.s_addr = inet_addr("127.0.0.1"); /* sockets are unsigned shorts, htons(x) ensures x is in network byte order, set the port to 7654 */ sa.sin_port = htons(7654); bytes_sent = sendto(sock, buffer, strlen(buffer), 0,(struct sockaddr*)&sa, sizeof sa); if (bytes_sent < 0) { printf("Error sending packet: %s\n", strerror(errno)); exit(EXIT_FAILURE); } close(sock); /* close the socket */ return 0; }
In this code, buffer is a pointer to the data to be sent, and buffer_length specifies the size of the data.
gethostbyname(3)
nsswitch.conf(5)
{{cite web}}
|title=
The de jure standard definition of the Sockets interface is contained in the POSIX standard, known as:
Information about this standard and ongoing work on it is available from the Austin website.
The IPv6 extensions to the base socket API are documented in RFC 3493 and RFC 3542.
Василий Михайлович Севергин Дата рождения 19 сентября 1765(1765-09-19) Место рождения Санкт-Петербург, Российская империя Дата смерти 29 ноября 1826(1826-11-29) (61 год) Место смерти Санкт-Петербург, Российская империя Страна Российская империя Научная сфера химия, минералогия, геологи…
Lambang TNI Angkatan Laut Buku Jalesveva Jayamahe: lukisan selayang pandang tentang keadaan ALRI kita dalam usia 15 tahun. Motto atau seruan TNI Angkatan Laut Indonesia adalah Jalesveva Jayamahe yang sering kali diterjemahkan sebagai Justru di Laut Kita Jaya. Motto ini sebenarnya berasal dari zaman Majapahit, yang angkatan lautnya sering memakai kata ini untuk membangkitkan semangat. Sebenarnya, ungkapan ini berasal dari Bahasa Sanskerta Jaleṣeva Jayamahe dan bisa dianalisis sebagai berikut: J…
Municipality in French Community, BelgiumChâtelet Tcheslet (Walloon)MunicipalityThe town hall. FlagCoat of armsLocation of Châtelet ChâteletLocation in Belgium Location of Châtelet in Hainaut Coordinates: 50°24′N 04°31′E / 50.400°N 4.517°E / 50.400; 4.517Country BelgiumCommunityFrench CommunityRegionWalloniaProvinceHainautArrondissementCharleroiGovernment • MayorDaniel Vanderlick (PS) • Governing party/iesPSArea •&…
Wapen van de familie De Thibault de Boesinghe De Thibault de Boesinghe is een West-Vlaamse notabele en adellijke familie met hoofdzakelijk landelijke wortels in de streek van Ieper. Geschiedenis Onder de notabelen van de stad en van de kasselrij Ieper, kwamen Thibaults voor vanaf de 13de eeuw. Christiaan Thibault was schepen van Ieper in het eerste kwart van de zestiende eeuw. Hij trouwde met Jeanne Kindt en ze hadden acht kinderen. De nakomelingen die ambtelijke functies uitoefenden, voornameli…
Gary Johnson, who in two spells as manager led Yeovil from the Conference to the Championship. This chronological list of managers of Yeovil Town Football Club comprises all those who have held the position of manager of the first team of Yeovil Town since the club was first admitted to the Southern League in 1923 and subsequently turned professional. Each manager's entry includes his dates of tenure and the club's overall competitive record (in terms of matches won, drawn and lost), honours won…
Kepek Barbonymus collingwoodii Status konservasiRisiko rendahIUCN90997659 TaksonomiKerajaanAnimaliaFilumChordataKelasActinopteriOrdoCypriniformesFamiliCyprinidaeGenusBarbonymusSpesiesBarbonymus collingwoodii (Günther, 1868) Tata namaSinonim taksonBarbodes collingwoodii (en) ProtonimBarbus collingwoodii lbs Kepek (Barbonymus collingwoodii) dalah spesies ikan bersirip kipas dalam genus Barbonymus yang ditemukan di aliran sungai dataran tinggi yang dingin dan berarus deras di Kalimantan yang endem…
Max PayneAliranTembak-menembak orang ketigaPengembangRemedy Entertainment (2001–2003; 2022–sekarang)Rockstar Studios (2012)PenerbitGathering of Developers (2001, PC)Rockstar GamesPenulisSam Lake (1–2)Dan Houser (3)Michael Unsworth (3)Rupert Humphries (3)Penyusun laguKärtsy Hatakka (1–2)Kimmo Kajasto (1–2)Perttu Kivilaakso (2)Health (3)Pelantar Microsoft Windows PlayStation 2 PlayStation 3 PlayStation 5 Xbox Xbox 360 Xbox One Xbox Series X/S Mac OS Game Boy Advance Android iOS Terbitan…
Artikel ini sebatang kara, artinya tidak ada artikel lain yang memiliki pranala balik ke halaman ini.Bantulah menambah pranala ke artikel ini dari artikel yang berhubungan atau coba peralatan pencari pranala.Tag ini diberikan pada Maret 2023. Morlam Bodyguard adalah sebuah seri drama series Thailand tahun 2022 garapan Thongchai Prasongsanti dan Nantharat Nanthaekkaphong serta ditulis oleh Suphachai Sittiaumponpan. Seri tersebut terdiri dari 44 episode dan menampilkan Point Cholawit Meetongcom, N…
Pour les articles homonymes, voir Payback. Payback (2023)Logo officiel de Payback 2023.Main event Seth Freakin Rollins (c) contre Shinsuke Nakamura pour le WWE World Heavyweight ChampionshipThème musical Too Good After Rising Hell par The StrutsInformationsFédération WWEDivision RawSmackDownDate 2 septembre 2023Spectateurs 14,584 personnesLieu PPG Paints ArenaVille(s) Pittsburgh (Pennsylvanie)Chronologie des événementsSummerSlam (2023)NXT No Mercy (2023)Chronologie des PaybackPayback (2020)…
Award Award 1969 Nobel Peace PrizeInternational Labour Organization (ILO)for creating international legislation insuring certain norms for working conditions in every country.Date 22 October 1969 (announcement) 10 December 1969 (ceremony) LocationOslo, NorwayPresented byNorwegian Nobel CommitteeFirst awarded1901WebsiteOfficial website ← 1968 · Nobel Peace Prize · 1970 → The 1969 Nobel Peace Prize was awarded to the United Nations agency International Labour Orga…
horizontale doorsnede kozijn met1: steendagmaat, 2: kozijndagmaat en 3: dagmaat glasopeningA: dag of dagzijde van het kozijn, B: dag van de glasopening en C: dag van het metselwerk. De dag, ook dagkant, dagzijde of negge is het binnenvlak van het materiaal dat een opening omsluit. De afmeting van de dag, de binnenwerkse maat of de afstand tussen de dagkanten, heet dagmaat. De dagmaat is bij een (enkele) deur, de vrije doorgang gemeten tussen de kozijnstijlen of anders gezegd: de deurbreedte minu…
Amuntai TengahKecamatanKantor kecamatan Amuntai TengahPeta lokasi Kecamatan Amuntai TengahNegara IndonesiaProvinsiKalimantan SelatanKabupatenHulu Sungai UtaraPemerintahan • Camat...Populasi • Total... jiwa jiwaKode Kemendagri63.08.05 Kode BPS6308050 Luas57,00 km² Amuntai Tengah (disingkat: AMT[1]) adalah sebuah kecamatan di Kabupaten Hulu Sungai Utara, Provinsi Kalimantan Selatan, Indonesia. Batas Wilayah Batas wilayah Kecamatan Amuntai Tengah adalah sebagai…
Kereta salju dengan dua kuda. Kereta salju yang ditarik seekor kuda. Kereta salju[a] atau kereta seluncur (bahasa Inggris: sled, sledge, atau sleigh) adalah kendaraan yang bergerak dengan cara meluncur di atas salju atau es. Kendaraan ini digunakan sebagai sarana transportasi. Kereta salju tidak memiliki roda, melainkan dilengkapi alas luncur atau memiliki bagian dasar yang mulus sehingga dapat meluncur. Meskipun demikian, kendaraan ini sering juga dipakai di atas permukaan lumpur, rumpu…
This article is part of a series onTaxation in the United States Federal taxation Alternative minimum tax Capital gains tax Corporate tax Estate tax Excise tax Gift tax Generation-skipping transfer tax Income tax Payroll tax Internal Revenue Service (IRS) Internal Revenue Code (IRC) IRS tax forms Revenue by state History Constitutional authority Taxpayer standing Court Protest Evasion Resistance State and local taxation State income tax Property tax Sales tax State and local tax deduction Use ta…
Surinamese singer-songwriter This biography of a living person needs additional citations for verification. Please help by adding reliable sources. Contentious material about living persons that is unsourced or poorly sourced must be removed immediately from the article and its talk page, especially if potentially libelous.Find sources: Jeangu Macrooy – news · newspapers · books · scholar · JSTOR (November 2017) (Learn how and when to remove this template…
An editor has performed a search and found that sufficient sources exist to establish the subject's notability. These sources can be used to expand the article and may be described in edit summaries or found on the talk page. The article may include original research, or omit significant information about the subject. Please help improve this article by adding citations to reliable sources. Unsourced material may be challenged and removed.Find sources: Phan Bá Vành's Rebellion –…
2017 American documentary film Boom for Real: The Late Teenage Years of Jean-Michel BasquiatFilm posterDirected bySara DriverProduced by Rachel Dengiz Sara Driver Starring Jean-Michel Basquiat Alexis Adler Felice Rosser Lee Quiñones Carlo McCormick Fab 5 Freddy Al Diaz Michael Holman Coleen Fitzgibbon Glenn O'Brien CinematographyAdam BennEdited byAdam KurnitzProductioncompanyHells Kitten ProductionsDistributed byMagnolia PicturesRelease dates September 8, 2017 (2017-09-08) (T…
Rumah Sakit Angkatan Udara Dr. M. SalamunBerkas:Gambar RSAU M. Salamun.jpgLambang Dinas Kesehatan TNI Angkatan UdaraDibentuk19 Agustus 1961NegaraIndonesiaCabangTNI Angkatan UdaraTipe unitRumah Sakit MiliterMotoHandal, Efisien, Bersih, Ramah, Indah, Nyaman, GemilangSitus webrsausalamun.com Rumah Sakit TNI AU Dr. M. Salamun Dinas Kesehatan TNI Angkatan Udara[1] adalah Rumah Sakit Militer tingkat II yang beradai di Kabupaten Bandung, Jawa Barat. RSAU Dr. M. Salamun mempunyai visi Menyelengg…
Batman Legends volume 2, #1 Batman Legends (retitled to simply Batman for its third and fourth volumes) was a monthly anthology comic book series published in the UK by Titan Magazines as part of their DC Comics 'Collector's' Edition' range. Initially published by Panini Comics for 41 issues between October 2003 and November 2006, Titan subsequently took over publication with the launch of the comic's second volume.[1] The title reprinted Batman-related comics originally published by DC …
Spanish actress and model Some of this article's listed sources may not be reliable. Please help this article by looking for better, more reliable sources. Unreliable citations may be challenged or deleted. (August 2018) (Learn how and when to remove this template message) Charlotte VegaBornCharlotte Elizabeth Vega (1994-02-10) 10 February 1994 (age 29)Madrid, Spain[1]OccupationActressYears active2010–present Charlotte Elizabeth Vega (born February 10, 1994) is a Spanish-Brit…
Lokasi Pengunjung: 3.144.233.89