The socket() system call function will help us to create an end point.
This end point will allow for example to connect a client to a server.
Indeed, both of them (client and server) will have a socket() system call function on their implementation.
In this tutorial of socket() we are going to see how to create a socket for a client and for a server.
Let's see first of all with the server snippet.
For the server, I'm using three files: server.c, debug.c and the header h.h.
/* server.c */ #include <sys/types.h> #include <sys/socket.h> #include <netdb.h> #include <stdio.h> #include <unistd.h> #include "h.h" void my_socket(t_s *s) { s->name = "TCP"; s->domain = AF_INET; s->type = SOCK_STREAM; s->pe = getprotobyname(s->name); s->fd = socket(s->domain, s->type, s->pe->p_proto); check_error(s->fd, -1); } int main() { t_s s; my_socket(&s); debug(&s); check_error(close(s.fd), -1); return 0; }
/* debug.c */ #include <stdio.h> #include <string.h> #include <errno.h> #include <stdlib.h> #include <unistd.h> #include "h.h" void debug(t_s *s) { printf("domain = %d\n", s->domain); printf("type = %d\n", s->type); printf("fd = %d\n", s->fd); printf("name = %s\n", s->name); printf("p_proto = %d\n", s->pe->p_proto); } void check_error(int test, int error) { if (test == error) { fprintf(stderr, "ERROR: %s\n", strerror(errno)); exit(EXIT_FAILURE); } }
#ifndef H_H_ #define H_H_ #include <netdb.h> /** * Structure */ typedef struct mystruct { int domain; int type; int fd; char *name; struct protoent *pe; } t_s; /** * Prototype */ void debug(t_s *); void check_error(int, int); #endif /* H_H_ */
So let's compile and execute them:
gcc server.c debug.c -o server ; ./server
domain = 2 type = 1 fd = 3 name = TCP p_proto = 6
Add new comment