Applying C - Socket Server
Written by Harry Fairhead   
Monday, 08 August 2022
Article Index
Applying C - Socket Server
WinSock Server


A WinSock Server

To make all of this work with WinSock you have to make the usual changes.


#include <sys/socket.h>


#include <winsock2.h>

You also need to add:

#define _WIN32_WINNT 0x501
#include <ws2tcpip.h>

to the start of the file and add the library files wsock32.a and ws2_32.a which you should find in mingw/lib to the libraries.

As before, the only other changes your program needs to make is to use recv and send in place of read and write and you need to start with a call to WSAStartup to initialize the sockets system:

WSADATA wsaData;
WSAStartup(0x202, &wsaData) ; 

where 0x202 specifies that you need at least WinSock 2.2.

In addition you need to use:

ioctlsocket(sockfd, FIONBIO , 0);

to set the socket to non-blocking.

#define _WIN32_WINNT 0x501
#include <ws2tcpip.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <winsock2.h>
int main(int argc, char** argv) {
    WSADATA wsaData;
    WSAStartup(0x202, &wsaData);
    struct addrinfo hints, *server;
    memset(&hints, 0, sizeof hints);
    hints.ai_family = AF_INET;
    hints.ai_socktype = SOCK_STREAM;
    hints.ai_flags = AI_PASSIVE;
    getaddrinfo(NULL, "1024", &hints, &server);
    int sockfd = socket(server->ai_family,
    ioctlsocket(sockfd, FIONBIO, 0);
    int result = bind(sockfd, server->ai_addr,
server->ai_addrlen); listen(sockfd, 10); struct sockaddr_storage client_addr; socklen_t addr_size = sizeof client_addr; int client_fd = accept(sockfd,
(struct sockaddr *) &client_addr, &addr_size); char buffer[2048]; char headers[] = "HTTP/1.0 200 OK\r\nServer: C\r\n
Content-type: text/html\r\n\r\n"; char html[] = "<html><head><title>Hello HTTP World
</head><body><p>Hello HTTP World</p></body>
</html>\r\n"; char data[2048] = {0}; snprintf(data, sizeof data, "%s %s", headers, html); for (;;) { int client_fd = accept(sockfd, (struct sockaddr *) &client_addr, &addr_size); if (client_fd > 0) { int n = recv(client_fd, buffer, 2048, 0); printf("%s", buffer); fflush(stdout); n = send(client_fd, data, strlen(data), 0); close(client_fd); } } return (EXIT_SUCCESS); }


  • Sockets are a general way of making a connection between two programs, perhaps running on different machines.

  • Sockets are a POSIX standard, but not a C standard. Windows supports a modified form of sockets via WinSock.

  • To use sockets you have to create a socket, connect it to an address and then transfer data.

  • Sockets come in two general types – client sockets, which actively connect to another socket and transfer data, and server sockets, which wait for a connection and then service it.

  • You create a socket using the socket function and you have to specify the type of connection and the detailed protocol in use.

  • To connect a socket you use the connect function, which accepts a struct which specifies the address of the socket to connect to.

  • A server socket has to be bound to an address, using the bind function, which it listens on for a client trying to connect.

  • A server socket also has a listen function, which activates it ready for a client to try to connect. The server then uses the accept function to create a connection.

  • Once a socket is connected to another socket data can be transferred as if it was a file. It is very easy to create a web client or a web server.

  • The simplest way to create a server is to use a blocking call to the accept function and leave the thread idle waiting for a client to connect.

  • A more useful way to handle the connection is in non-blocking mode which allows the thread to do something else while waiting.



Related Articles

Raspberry Pi And The IoT In C

Getting Started With C/C++ On The Micro:bit

Now available as a paperback or ebook from Amazon.

Applying C For The IoT With Linux

  2. Kernel Mode, User Mode & Syscall
  3. Execution, Permissions & Systemd
    Extract Running Programs With Systemd
  4. Signals & Exceptions
    Extract  Signals
  5. Integer Arithmetic
    Extract: Basic Arithmetic As Bit Operations
  6. Fixed Point
    Extract: Simple Fixed Point Arithmetic
  7. Floating Point ***NEW
  8. File Descriptors
    Extract: Simple File Descriptors 
    Extract: Pipes 
  9. The Pseudo-File System
    Extract: The Pseudo File System
    Extract: Memory Mapped Files 
  10. Graphics
    Extract: framebuffer
  11. Sockets
    Extract: Sockets The Client
    Extract: Socket Server
  12. Threading
    Extract:  Pthreads
    Extract:  Condition Variables
    Extract:  Deadline Scheduling
  13. Cores Atomics & Memory Management
    Extract: Applying C - Cores 
  14. Interupts & Polling
    Extract: Interrupts & Polling 
  15. Assembler
    Extract: Assembler

Also see the companion book: Fundamental C



To be informed about new articles on I Programmer, sign up for our weekly newsletter, subscribe to the RSS feed and follow us on Twitter, Facebook or Linkedin.


Azul Intelligence Cloud Expands Support

Azul has announced that its cloud analytics solution, Azul Intelligence Cloud, now supports Oracle JDK and any OpenJDK-based distribution. More DevOps teams will now benefit from its ability to b [ ... ]

Gemini 1.5 Pro Now Available

Google has released Gemini 1.5 Pro with improvements including Native Audio Understanding, System Instructions, and a JSON mode.

More News

raspberry pi books



or email your comment to:

Last Updated ( Wednesday, 28 December 2022 )