Network Programming in C
Network programming in C uses the Berkeley sockets API, available on POSIX and Winsock (Windows). Understanding sockets is foundational for servers, IoT, and embedded connectivity.
TCP Server
#include <sys/socket.h>
#include <netinet/in.h>
#include <unistd.h>
int server_fd = socket(AF_INET, SOCK_STREAM, 0);
struct sockaddr_in addr = {
.sin_family = AF_INET,
.sin_port = htons(8080),
.sin_addr.s_addr = INADDR_ANY
};
bind(server_fd, (struct sockaddr *)&addr, sizeof addr);
listen(server_fd, 5);
int client = accept(server_fd, NULL, NULL);
char buf[256];
ssize_t n = read(client, buf, sizeof buf - 1);
close(client);
close(server_fd);
TCP Client
int sock = socket(AF_INET, SOCK_STREAM, 0);
struct sockaddr_in server = {
.sin_family = AF_INET,
.sin_port = htons(8080),
};
inet_pton(AF_INET, "127.0.0.1", &server.sin_addr);
connect(sock, (struct sockaddr *)&server, sizeof server);
write(sock, "Hello", 5);
close(sock);
UDP
int sock = socket(AF_INET, SOCK_DGRAM, 0);
/* sendto / recvfrom instead of connect/read/write */
Non-blocking I/O
#include <fcntl.h>
int flags = fcntl(fd, F_GETFL, 0);
fcntl(fd, F_SETFL, flags | O_NONBLOCK);
/* Use select(), poll(), or epoll() for multiplexing */
Error Handling
Always check return values. -1 from socket calls sets errno. Use getaddrinfo for portable hostname resolution instead of deprecated gethostbyname.
Common Pitfalls
- Treating compiler warnings as optional rather than actionable feedback.
- Skipping error checks on library and system calls.
- Copy-pasting examples without adapting to your project’s conventions.
Best Practices
- Enable strict compiler warnings and fix them before merging.
- Write small, testable units with clear input/output contracts.
- Document non-obvious invariants and preconditions.
- Use version control and code review for every change.
Memory and Performance Notes
Each read/write may syscall into the kernel. Buffer data in userspace to reduce syscall count.
Exercise
Implement an echo server that accepts connections and sends back whatever the client writes until disconnect.
Hint: Handle partial reads — read may return fewer bytes than requested. Loop until complete message or EOF.
Summary
Apply these concepts in small programs before moving to larger projects. Combine with adjacent topics in the learning path for deeper mastery.
Real-World Application
These concepts appear in production codebases — from operating system kernels to embedded firmware. Study open-source projects that use this topic extensively to see idiomatic patterns at scale.
Debugging Checklist
- Reproduce the issue with the smallest possible input.
- Enable compiler warnings and sanitizers.
- Use a debugger to inspect state at the failure point.
- Verify assumptions about types, sizes, and return values.
- Compare working and broken code paths side by side.
- Write a regression test once the bug is fixed.
Further Reading
Consult the ISO C standard, Effective C by Robert C. Seacord, and your compiler documentation for platform-specific behavior.
Quick Reference
Review the code examples on this page before starting the exercise. Type them manually to build muscle memory.
Additional Examples
Consider how this topic applies in a larger project:
// Break the problem into smaller functions
// Test each function independently
// Integrate incrementally
Working through variations of the examples above builds deeper understanding than reading alone.
Interview and Review Questions
- Explain the core concept of this topic in your own words.
- What happens when this code runs with edge-case input (empty, null, zero, max value)?
- How would you debug a bug related to this topic in production?
- What are the performance implications of the approach shown here?
- How does this feature compare to the equivalent in another language you know?
Related Topics in This Path
Review adjacent pages in the learning path before and after this one. Concepts build on each other — skipping ahead often leads to confusion when later pages assume mastery of earlier material.
Return to the section index if you need to fill gaps in prerequisite knowledge.