TEZZ CONNECTBlog

Blog / Internet Technology & Updates / Network Sockets

NETWORKING FUNDAMENTALS · PRACTICAL GUIDE

What Is a Network Socket? IP Addresses, Ports, TCP and UDP Explained

A practical guide to the endpoints behind everyday internet communication—from IP addresses and port numbers to TCP and UDP socket lifecycles.

By Suraj Vishwakarma · Published by TEZZ CONNECT · Published 27 November 2026 · Updated 27 November 2026

Network engineer studying client-server sockets, IP addresses, ports, TCP and UDP

When you open a website, join an online meeting, send a message or play a multiplayer game, an application has to exchange data with another application. IP networking can move packets between devices, and transport protocols can deliver data to the right destination process. But application software still needs a practical interface for opening communication, sending bytes or messages, receiving data and closing the conversation. That interface is commonly called a network socket.

Sockets are often described as communication endpoints. That description is useful, but a socket is more than an IP address or a port number. It is an operating-system programming abstraction through which a process interacts with a communication protocol. A socket may represent a TCP connection, a UDP communication endpoint, a local inter-process channel or another supported communication mechanism. The exact behaviour depends on its address family, type, protocol and operating-system API.

This guide explains sockets from the network user's point of view and from the application developer's point of view. It separates IP addressing from port addressing, follows the lifecycle of a TCP server and client, explains datagram sockets, and shows how to investigate common connection failures. The examples use familiar Internet concepts, while noting where operating systems and programming languages differ.

1. What is a network socket?

A network socket is an endpoint exposed to an application for communication. A program asks the operating system to create a socket, then uses that socket to perform operations such as connecting to a remote service, accepting an incoming connection, sending data or receiving data.

Think of a delivery system. An IP address is similar to the street address of a building. A port number is similar to the department or desk inside that building. The socket is the communication endpoint that an application uses to exchange information through that address and transport service. The analogy is not exact—ports are protocol-specific numbers, not physical rooms—but it helps explain why an IP address alone is not enough to identify a particular application conversation.

On common operating systems, creating a socket returns a handle: on Unix-like systems it is usually a file descriptor, while other platforms expose their own socket handle types. The application passes that handle to later calls. The kernel maintains the associated protocol state, buffers and endpoint information.

A socket is not the same thing as a physical network port, such as an Ethernet jack, and it is not the same as a TCP or UDP port number. These terms are easy to confuse. A physical port is hardware. A transport port is a number in a TCP or UDP header. A socket is an application-facing communication object.

2. How IP addresses and port numbers work together

An IP address identifies a network-layer destination interface or endpoint. IPv4 addresses are 32 bits; IPv6 addresses are 128 bits. Routers use IP addressing to forward packets across networks. Once a packet reaches the destination host, the transport protocol uses additional information to deliver it to the appropriate application endpoint.

TCP and UDP each have source and destination port fields. These are 16-bit numbers, so the numeric range is 0 through 65,535. A port number has meaning in the context of a transport protocol: TCP port 443 and UDP port 443 are distinct transport endpoints, even though they use the same numeric value. The IANA registry records service names and port assignments, but a registered number is not proof that a particular host is running that service.

For example, a browser might connect from a temporary local TCP port such as 51824 to a web server at 203.0.113.20 on TCP port 443. The server listens on its chosen local address and port. The client operating system generally selects an available ephemeral source port automatically. The exact port is not a permanent identity for the user's device; it belongs to that particular socket or flow while it is in use.

In simplified terms, a TCP connection is identified by the combination of source IP address, source port, destination IP address and destination port, together with the transport protocol. This is often called the four-tuple plus protocol. It allows many clients to connect to the same server IP address and server port at the same time because each client connection has a different source endpoint. IPv6 and modern networking add further details, but the principle remains useful.

UDP has no connection handshake in the TCP sense. Applications still use local and remote addressing information to send and receive datagrams, and the operating system can associate a UDP socket with a local port or a specific peer. A UDP socket may receive datagrams from multiple remote senders when it is not restricted to one peer.

Common service examples include HTTPS on TCP port 443, DNS commonly using UDP or TCP port 53, and SSH commonly using TCP port 22. These are conventions and registry entries, not guarantees: services can be configured to use other ports, and firewalls can block traffic regardless of the port's registered name.

3. Socket families, types and protocols

When an application creates a socket, it normally specifies an address family, a socket type and, optionally, a protocol. These choices tell the operating system what kind of communication is required.

Address families

AF_INET is commonly used for IPv4 Internet sockets, and AF_INET6 for IPv6. AF_UNIX (also called AF_LOCAL on some systems) provides local communication between processes on the same machine without sending packets over an IP network. Other families support specialised networking, packet capture or platform-specific functions.

Socket types

SOCK_STREAM provides a reliable, ordered byte stream when used with TCP on the Internet. The application reads and writes a continuous sequence of bytes; it does not receive a promise that each write will correspond to one matching read. TCP handles segmentation, retransmission and ordering underneath the application interface.

SOCK_DGRAM provides datagram-oriented communication, commonly used with UDP. Each send operation creates a message boundary. A receiver obtains datagrams, not an automatically reassembled reliable byte stream. Datagrams can be lost, duplicated or arrive out of order, so applications that need stronger guarantees must implement suitable mechanisms themselves or choose another protocol.

Other socket types exist. For example, raw sockets can expose lower-level protocol access and are often restricted because they can be used to construct or inspect packets. The available types and permissions vary by operating system.

Protocol selection

In many common cases, the operating system selects the expected protocol from the address family and socket type when the protocol argument is zero. A TCP stream socket and a UDP datagram socket are the familiar Internet examples. Developers should consult the platform API rather than assume every combination is portable.

4. The lifecycle of a TCP server socket

A TCP server normally creates a listening socket and waits for clients. The classic socket API expresses this as a sequence of operations: socket(), bind(), listen() and accept(). Each call has a separate purpose.

Step 1: socket()

The server calls socket() to request a socket of the required family and type. For an IPv4 TCP server, a typical choice is AF_INET with SOCK_STREAM. The returned handle refers to a socket object, but it is not yet listening for incoming connections.

Step 2: bind()

The server calls bind() to associate the socket with a local address and port. It might bind to one specific interface address or to a wildcard address that means the service should accept connections arriving through eligible local interfaces. Binding to a wildcard address can make a service reachable through more interfaces than intended, so the choice should match the deployment's security requirements.

A bind operation can fail if the address is unavailable, the port is already in use under the operating system's rules, or the process lacks permission for a restricted port. Address reuse options can affect restart and multi-process behaviour, but their semantics differ across systems. They should not be enabled blindly as a generic fix for every “address already in use” error.

Step 3: listen()

For a connection-oriented socket such as TCP, listen() marks the bound socket as passive: it is prepared to accept incoming connection requests. The call also accepts a backlog parameter that influences how many pending connections the system may queue. The backlog is not a promise that the application can handle that many active users, nor is it a universal fixed count; operating systems may cap or interpret it according to their own rules.

Step 4: accept()

The server calls accept() to obtain a new socket for a client connection. This distinction is essential: the listening socket remains available to accept more clients, while the newly returned connected socket is used to exchange data with one particular client. A server can repeat accept operations and manage many connected sockets concurrently.

In a simple blocking server, accept() waits until a connection is ready. In a non-blocking or event-driven server, the program monitors readiness and accepts connections when the operating system reports that the listening socket can be serviced. High-concurrency servers often use mechanisms such as select(), poll(), epoll or platform-specific event facilities.

5. How a TCP client connects

A TCP client generally creates a stream socket and calls connect() with the server's address and port. The operating system selects a local source address and an available source port when needed. The TCP implementation then performs connection establishment with the remote endpoint.

The familiar TCP three-way handshake uses SYN, SYN-ACK and ACK segments. It synchronises sequence numbers and establishes the protocol state required for a bidirectional byte stream. The application sees a successful connection result only after the relevant connection-establishment process succeeds. The handshake does not mean the application has authenticated the server or encrypted the data; TLS or another security protocol is needed for those properties.

A connection attempt can fail for different reasons. The remote host may be unreachable, a firewall may silently drop packets, the server may not be listening, the port may be actively rejected, DNS may return an unsuitable address, or the connection may time out before completion. These failures have different symptoms and should not all be labelled “the internet is down.”

Modern clients may resolve a hostname to multiple IPv4 and IPv6 addresses. A dual-stack client that waits too long for one address family can make connection setup feel slow even when another path works. Happy Eyeballs, specified in RFC 8305, describes a strategy for making staggered connection attempts across candidate addresses so a broken or slow path does not unnecessarily delay the user. The successful connection attempt is retained and competing attempts are cancelled.

After a TCP connection is established, applications exchange a stream of bytes. TCP provides ordered delivery and retransmission for data that is lost in transit, but it does not preserve application message boundaries. If an application sends a 1,000-byte message, the receiver might read it in several smaller chunks or receive multiple application writes in one read. Application protocols therefore need framing—for example, fixed-size records, length prefixes, delimiters or a structured protocol format.

6. UDP sockets: messages without a TCP connection

UDP is a connectionless transport protocol. An application can create a datagram socket and send a message to a destination address without first establishing a TCP-style connection. The receiver obtains datagrams, each with its own message boundary, if they arrive and are delivered to the socket.

UDP does not provide TCP's built-in reliable, in-order byte stream. It does not automatically retransmit lost datagrams, suppress duplicates or reorder messages into the original sequence. An application can add acknowledgements, sequence numbers, retransmission, congestion control and encryption, but those mechanisms must be designed carefully. Simply choosing UDP does not make an application faster or more scalable in every environment.

UDP is useful when the application benefits from message-oriented delivery and can tolerate loss, or when the application protocol supplies its own reliability and congestion behaviour. DNS queries, real-time media and many discovery or telemetry systems use UDP in appropriate circumstances. Modern protocols such as QUIC use UDP as a substrate while implementing sophisticated transport features above it; that does not make QUIC equivalent to an unmodified UDP application.

A UDP server often creates a datagram socket, binds it to a local address and port, and waits for datagrams with a receive operation. It can reply to the sender address returned with the datagram. A UDP client can use a send-to operation for each destination or connect its UDP socket to a peer. In the UDP case, connect() configures a default peer and may filter received datagrams; it does not perform a TCP handshake or create TCP-like delivery guarantees.

7. TCP and UDP sockets compared

The correct choice depends on application requirements, not on a simple rule that one protocol is always better.

PropertyTCP stream socketUDP datagram socket
Communication modelConnection-orientedConnectionless at transport level
Data modelContinuous byte streamSeparate datagrams
DeliveryReliable retransmission and ordered byte deliveryNo built-in guarantee of delivery or ordering
Message boundariesNot preservedPreserved per datagram
SetupConnection establishment handshakeNo TCP-style handshake
Typical usesWeb sessions, SSH, file transfer, many APIsDNS, real-time media, telemetry, discovery
Application responsibilityDefine message framing and application semanticsHandle loss, ordering and reliability if required

TCP's reliability is useful for data where missing or reordered bytes would break the application. UDP's message model can suit time-sensitive or request-response workloads, but applications still need to consider congestion, security and network fairness. A high-rate UDP sender that ignores congestion can harm other traffic and may be throttled or dropped by networks.

8. What does a socket address contain?

A socket address is the structured address information used by the API. For Internet sockets it typically includes an address family, an IP address and a port number. IPv6 socket address structures also include fields such as flow information and a scope identifier where relevant. The exact in-memory structure is API-specific.

IPv6 link-local addresses illustrate why a plain address string may not always be enough. The same link-local address range can exist on multiple network interfaces. A scope identifier can tell the operating system which interface is intended. Without the correct scope, a program may not know where to send the packet.

Applications usually should not manually parse hostnames into socket structures. Name-resolution APIs such as getaddrinfo() can return one or more candidate socket addresses for a hostname and service. This supports IPv4, IPv6 and service-name resolution more consistently than hard-coding a single address structure. It also helps applications handle multiple candidate addresses and address-family preferences.

9. Blocking, non-blocking and asynchronous sockets

With a blocking socket, an operation such as accept() or recv() may wait until the requested event occurs. This model is straightforward and can be suitable for small programs, command-line tools or one-connection-at-a-time services. But a program that blocks one thread per slow client can consume significant resources as concurrent connections increase.

A non-blocking socket returns control when an operation cannot complete immediately, commonly with a platform-specific indication that the operation would block. The application can then do other work and retry when the socket becomes ready. Non-blocking operation requires careful handling of partial sends, partial reads, connection progress and error states.

Event-driven programs use readiness notification or completion-based asynchronous APIs. On Linux, epoll is widely used for scalable readiness notification. Other operating systems provide different facilities. High-level runtimes often wrap these mechanisms so application developers can use promises, async/await or event loops instead of manually managing every low-level operation.

Concurrency does not eliminate resource limits. Each open connection consumes kernel and application resources. Servers need limits for open sockets, memory buffers, idle timeouts, request rates and work queues. A socket can be technically connected while the application is overloaded or unable to make useful progress.

10. Socket closure, half-close and timeouts

Applications should close sockets when communication is finished. On a TCP connection, closing a socket normally causes the local endpoint to begin an orderly shutdown, though the precise timing depends on unread data, pending writes, shutdown options and operating-system behaviour. TCP uses FIN and ACK exchanges to close directions of the connection.

TCP is full duplex: each direction can be shut down separately. A half-close lets an application indicate that it will send no more data while still receiving data from the peer. This can be useful in protocols where the end of a request is signalled by closing the sending direction, while the response is still expected.

An abrupt reset is different from an orderly close. A TCP RST indicates that the connection is being reset rather than gracefully finished. Applications may see a reset when a peer process exits unexpectedly, a device or middlebox rejects a connection, or the application interacts with a socket in an invalid state. A reset is not automatically proof of a malicious attack.

Timeouts are an application design responsibility as well as a transport concern. A server should decide how long to wait for a client to send a request, how long an operation may take, and how long an idle connection can remain open. A client should distinguish DNS resolution time, connection-establishment time, TLS handshake time, request time and response time where possible. One broad timeout can make diagnosis difficult.

11. Common socket errors and what they mean

Address already in use: another socket may already be bound to the requested address and port, or the operating system's reuse and connection-state rules may prevent the new bind. Identify the process using the port before changing socket options.

Connection refused: the destination host or an intermediary actively rejected the attempt. A common cause is that no service is listening on the target port, but a firewall can also send a rejection.

Connection timed out: no successful connection response arrived within the allowed time. Possible causes include packet filtering, routing failure, server overload, an unavailable host or a path problem. A timeout does not identify which device dropped the traffic.

Network is unreachable: the local system does not have a usable route for the destination, or the network stack reports that the destination network cannot be reached.

Broken pipe or connection reset: the peer may have closed or reset the connection while the application was still trying to exchange data. Applications should handle these conditions rather than assume every send succeeds.

Too many open files: on many Unix-like systems, sockets consume file descriptors. A process that leaks sockets or opens too many concurrent connections can hit a descriptor limit. Inspect process limits and ensure every socket is closed on success, failure and cancellation paths.

12. A practical troubleshooting workflow

When an application cannot connect, work from the name and route toward the application listener. First confirm the hostname resolves to the expected IPv4 or IPv6 addresses. Compare the result with the server's intended public or private address. If a hostname returns several addresses, test them individually where appropriate.

Next verify basic reachability and routing. A failed ping does not prove that a TCP service is unreachable because ICMP may be filtered. Use route inspection and targeted connection tests. Check whether the destination port is reachable from the same network as the affected client; a test from a different network may follow a different path or firewall policy.

On the server, confirm that the process is running and listening on the expected address and port—not only on loopback if remote clients need access. Check the firewall, cloud security rules, NAT or port-forwarding configuration, and any reverse proxy between the client and service. Confirm that the service is bound to the correct interface and address family.

For TCP, inspect the connection state and capture packets when necessary. A SYN with no response suggests a different failure pattern from a SYN followed by RST. A completed handshake followed by an application stall points beyond basic TCP reachability: investigate TLS, protocol framing, authentication, server capacity and application logs.

For UDP, remember that a successful local send call only means the operating system accepted the datagram for transmission. It does not confirm that the remote application received or processed it. If the application needs confirmation, it must define an acknowledgement or response mechanism. Packet captures at both endpoints can help identify where datagrams disappear.

Useful Linux tools include ss for socket statistics, ip route for route inspection, getent hosts for name lookup, nc for basic TCP or UDP tests, and tcpdump or Wireshark for packet analysis. Tool options and availability differ by operating system. Avoid exposing sensitive payloads or credentials when collecting packet captures.

13. Socket security: listening safely

A listening socket is an entry point into an application. Bind only to the interfaces that need to receive traffic. A development server intended for local testing should not accidentally listen on every network interface. In production, expose only the ports required by the service and apply firewall rules at the host, network and cloud layers where appropriate.

Validate all data received over a socket. TCP reliability does not make the payload trustworthy, and UDP datagrams are no more trustworthy because they arrive quickly. Treat remote input as untrusted, enforce message-size limits, handle malformed framing, and avoid allocating unlimited memory based on a claimed message length.

Use encryption and authentication where the application requires confidentiality, integrity or peer identity. A successful TCP connection does not provide those protections. TLS is commonly used to secure application protocols over TCP, while QUIC integrates cryptographic protection into its transport design over UDP. Certificates, hostname verification, key management and protocol configuration all matter.

Rate-limit expensive operations and protect against resource exhaustion. A server can be attacked through large numbers of connection attempts, slow clients, oversized messages or expensive application requests. Connection limits, read and write deadlines, request quotas, reverse proxies and monitoring can reduce exposure, but must be tuned to the real workload.

14. A simple mental model: from browser to server

Imagine opening a secure website. The browser resolves the hostname and obtains one or more candidate IP addresses. It selects an address and attempts a connection to the service port. Its operating system creates or uses a client socket, chooses a source port and begins the transport connection. The server has a listening socket bound to an address and port. When the connection arrives, the server accepts it and receives a separate connected socket for that client.

The browser and server then negotiate the security and application protocols. They exchange data through the connected sockets. The transport layer handles its responsibilities; the application layer interprets messages and decides what the bytes mean. When the session is finished, the endpoints close the connection and release resources.

This model explains why several separate checks are needed when a website fails. DNS can work while a TCP connection fails. TCP can connect while TLS fails. TLS can succeed while the HTTP application returns an error. Each stage uses different protocols, state and logs. A socket is the application-facing endpoint that helps software participate in this layered process; it does not replace the layers beneath or above it.

15. Choosing the right socket model

For a conventional request-response application that needs reliable ordered delivery, TCP stream sockets are a common starting point. The application must define message framing and sensible timeouts. For small datagrams, discovery, telemetry or real-time data where the application can handle loss or has a protocol designed around datagrams, UDP sockets may be appropriate. For local communication between processes on one machine, a Unix-domain socket can avoid IP networking entirely and may offer useful access-control properties.

Do not select a protocol based only on a benchmark headline. Measure the real application under realistic packet loss, latency, concurrency and device constraints. Include connection setup, encryption, server processing, retransmissions, DNS, address-family selection and the cost of maintaining idle connections. A fast local test may not represent a mobile connection or a congested broadband path.

The most important distinction is that a socket is an API abstraction, while TCP and UDP are transport protocols with different delivery models. Understanding that separation makes application behaviour easier to reason about, and makes network troubleshooting more precise.

Frequently asked questions

1. What is a network socket in simple words?

A network socket is an endpoint that an application uses to send and receive data through an operating system's networking interface. It is associated with a communication family, type and protocol, and may use IP addresses and port numbers.

2. Is a socket the same as an IP address?

No. An IP address identifies a network-layer destination, while a socket is an application-facing communication object. Internet socket addressing commonly combines an IP address and a transport port, along with the protocol context.

3. Is a socket the same as a port?

No. A transport port is a numeric field used by TCP or UDP to identify an application endpoint on a host. A socket is the operating-system abstraction that applications use to communicate through that endpoint.

4. What is the difference between TCP and UDP sockets?

A TCP stream socket provides a reliable, ordered byte stream after connection establishment. A UDP datagram socket sends and receives separate messages without built-in delivery or ordering guarantees.

5. What do bind(), listen() and accept() do?

bind() associates a socket with a local address and port. listen() marks a connection-oriented socket as ready to accept incoming connections. accept() returns a new connected socket for a client while the listening socket remains available for other clients.

6. What does connect() do?

For a TCP socket, connect() starts connection establishment with a remote endpoint. For a UDP socket, it usually sets a default peer and may restrict received datagrams to that peer; it does not create a TCP-style handshake.

7. Can multiple clients connect to the same server port?

Yes. A listening server socket can accept many connections. Each established TCP connection is distinguished by its local and remote addresses and ports, so many clients can use the same server IP address and port simultaneously.

8. Why can TCP read() return fewer bytes than the sender wrote?

TCP is a byte stream, not a message protocol. A read operation returns the bytes currently available up to the requested amount. Applications must implement framing with lengths, delimiters or another message format.

9. Does a successful UDP send prove the receiver got the data?

No. A successful send generally means the local system accepted the datagram for transmission. UDP does not guarantee delivery, so an application that needs confirmation must implement a response or acknowledgement mechanism.

10. How can I see which ports are listening on my computer?

On Linux, commands such as ss -lntup can display listening TCP and UDP sockets, subject to permissions and tool availability. Other operating systems provide their own socket and network inspection commands.

Sources and further reading