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

Cbookcover

A WinSock Server

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

Replace:

#include <sys/socket.h>

by:

#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,
            server->ai_socktype,
            server->ai_protocol);
    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
</title>
</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); }

Summary

  • 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

  1. C,IoT, POSIX & 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
  8. File Descriptors
    Extract: Simple File Descriptors 
    Extract: Pipes 
  9. The Pseudo-File System
    Extract: The Pseudo File System
    Extract: Memory Mapped Files ***NEW
  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

<ASIN:1871962609>

<ASIN:1871962463>

<ASIN:1871962617>

<ASIN:1871962455>

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.

Banner


Stack Overflow On Google Cloud
06/03/2024

Stack Overflow and Google Cloud have announced a partnership to deliver new gen AI-powered capabilities to developers through the Stack Overflow platform, Google Cloud Console, and Gemini for Google C [ ... ]



iOS 17.4 Released With Support For App Stores In The EU
06/03/2024

I have written about Apple's approach to complying with regulation, characterizing it as malicious compliance. It also seems that Apple is a master of creating the unintended consequence and letting i [ ... ]


More News

raspberry pi books

 

Comments




or email your comment to: comments@i-programmer.info



Last Updated ( Wednesday, 28 December 2022 )