1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80
|
#include <netinet/in.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <arpa/inet.h>
#include <stdlib.h>
#include <netdb.h>
#include <stdio.h>
int get_socket();
void get_bind(int s, int port);
void get_connect(int s);
void xwrite(int fd, void *buf, int len);
void xclose(int fd);
int get_socket()
{
int s;
if ((s = socket(PF_INET, SOCK_STREAM, 0)) == -1)
{
xwrite(2, "socket error\n", 13);
exit(EXIT_FAILURE);
}
return (s);
}
void get_bind(int s, int port)
{
struct sockaddr_in addr;
addr.sin_family = AF_INET;
addr.sin_port = htons(port);
addr.sin_addr.s_addr = INADDR_ANY;
if (bind(s, (struct sockaddr *)&addr, sizeof(addr)) == -1)
{
xwrite(2, "bind error\n", 11);
exit(EXIT_FAILURE);
}
return ;
}
void get_connect(int s)
{
struct sockaddr_in cli;
int len;
int cs;
if (listen(s, 42) == -1)
{
xwrite(2, "listen error\n", 13);
exit(EXIT_FAILURE);
}
len = sizeof(cli);
if ((cs = accept(s, (struct sockaddr *)&cli, (socklen_t *)&len) == -1))
{
xwrite(2, "accept error\n", 13);
exit(EXIT_FAILURE);
}
printf("cs : %d\n", cs);
xwrite(cs, "----connection granted----\n", 27);
xclose(cs);
}
int main(int ac, char **av)
{
int s;
if (ac < 2)
{
xwrite(2, "Gimme da port\n", 14);
exit(EXIT_FAILURE);
}
s = get_socket();
get_bind(s, atoi(av[1]));
get_connect(s);
xclose(s);
return (0);
} |
Partager