Mercurial > public > hey
changeset 1:58952f1fb8da
minimal socket example
author | Dennis <dennisconcepcionmartin@gmail.com> |
---|---|
date | Mon, 17 Jul 2023 18:05:20 +0100 |
parents | 5d2832cac043 |
children | 052cf5cf100a |
files | README.md src/main.c |
diffstat | 2 files changed, 46 insertions(+), 1 deletions(-) [+] |
line wrap: on
line diff
--- a/README.md Mon Jul 17 10:31:32 2023 +0100 +++ b/README.md Mon Jul 17 18:05:20 2023 +0100 @@ -1,1 +1,7 @@ # web-server + +## References + +- [What is a web server](https://developer.mozilla.org/en-US/docs/Learn/Common_questions/Web_mechanics/What_is_a_web_server) +- [HTTP Protocol](https://www.rfc-editor.org/rfc/pdfrfc/rfc7231.txt.pdf) +- [Socket programming Oracle](https://docs.oracle.com/cd/E19253-01/817-4415/6mjum5som/index.html)
--- a/src/main.c Mon Jul 17 10:31:32 2023 +0100 +++ b/src/main.c Mon Jul 17 18:05:20 2023 +0100 @@ -1,7 +1,46 @@ #include <stdio.h> +#include <stdlib.h> +#include <string.h> +#include <sys/types.h> +#include <sys/socket.h> +#include <netinet/in.h> +#include <arpa/inet.h> + int main() { - printf("Hello, world!\n"); + int socketfd = socket(AF_INET, SOCK_STREAM, 0); + + if (socketfd == -1) { + printf("Socket creation failed\n"); + exit(1); + } + + struct sockaddr_in sin; + memset(&sin, 0, sizeof(sin)); + sin.sin_family = AF_INET; + sin.sin_addr.s_addr = inet_addr("127.0.0.1"); + sin.sin_port = htons(5050); + + if (bind(socketfd, (struct sockaddr*)&sin, sizeof(sin)) == -1) { + printf("Socket binding failed\n"); + } + + //if (connect(socketfd, (struct sockaddr*)&sin, sizeof(sin) == -1)) { + //printf("Socket connection failed\n"); + //} + + if (listen(socketfd, 10) == -1) { + printf("Listen failed\n"); + } + + char sendBuff[50] = "Hello world\n"; + + while (1) { + int connfd = accept(socketfd, (struct sockaddr*)NULL, NULL); + send(connfd, sendBuff, sizeof(sendBuff), 0); + shutdown(connfd, 2); + } + return 0; }