Mercurial
comparison seobeo/s_linux_network.c @ 1:adcfad6e86fb
Updated naming and separated out some logic within seobeo.
| author | June Park <parkjune1995@gmail.com> |
|---|---|
| date | Wed, 24 Sep 2025 09:11:20 -0700 |
| parents | |
| children | 2758f5527d2b |
comparison
equal
deleted
inserted
replaced
| 0:5695ef413be0 | 1:adcfad6e86fb |
|---|---|
| 1 #include "seobeo/seobeo.h" | |
| 2 | |
| 3 int Seobeo_CreateSocket(int32 stream, char* port, int32 backlog) | |
| 4 { | |
| 5 int32 sock_fd; | |
| 6 struct addrinfo hints, *server_infos, *free_server_info; | |
| 7 int32 yes = 1; // Need this for setsockopt | |
| 8 | |
| 9 memset(&hints, 0, sizeof(hints)); | |
| 10 if (stream) | |
| 11 { | |
| 12 hints.ai_family = AF_INET; | |
| 13 hints.ai_socktype = SOCK_STREAM; | |
| 14 hints.ai_protocol = IPPROTO_TCP; | |
| 15 hints.ai_flags = AI_PASSIVE; | |
| 16 } | |
| 17 else | |
| 18 { | |
| 19 hints.ai_family = AF_INET; | |
| 20 hints.ai_socktype = SOCK_DGRAM; | |
| 21 hints.ai_protocol = IPPROTO_UDP; | |
| 22 hints.ai_flags = AI_PASSIVE; | |
| 23 } | |
| 24 | |
| 25 | |
| 26 if (getaddrinfo(NULL, port, &hints, &server_infos) != 0) | |
| 27 { | |
| 28 perror("getaddrinfo"); | |
| 29 return -1; | |
| 30 } | |
| 31 | |
| 32 for | |
| 33 ( | |
| 34 free_server_info = server_infos; | |
| 35 free_server_info != NULL; | |
| 36 free_server_info = free_server_info->ai_next | |
| 37 ) | |
| 38 { | |
| 39 if | |
| 40 ( | |
| 41 (sock_fd = socket( | |
| 42 free_server_info->ai_family, free_server_info->ai_socktype, | |
| 43 free_server_info->ai_protocol | |
| 44 )) == -1 | |
| 45 ) | |
| 46 { | |
| 47 perror("socket"); | |
| 48 continue; | |
| 49 } | |
| 50 | |
| 51 if (setsockopt(sock_fd, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(yes)) == -1) | |
| 52 { | |
| 53 perror("setsockopt"); | |
| 54 continue; | |
| 55 } | |
| 56 | |
| 57 if (bind(sock_fd, free_server_info->ai_addr, free_server_info->ai_addrlen) == -1) | |
| 58 { | |
| 59 close(sock_fd); | |
| 60 perror("setsockopt"); | |
| 61 continue; | |
| 62 } | |
| 63 | |
| 64 // UDP should be non blocking | |
| 65 if(!stream) | |
| 66 { | |
| 67 if (fcntl(sock_fd, F_SETFL, O_NONBLOCK) != 0) | |
| 68 { | |
| 69 close(sock_fd); | |
| 70 perror("v_network: Couldn't make socket non-blocking\n"); | |
| 71 return -1; | |
| 72 } | |
| 73 } | |
| 74 | |
| 75 // binded to a open server infos; | |
| 76 break; | |
| 77 } | |
| 78 | |
| 79 // No longer need these values | |
| 80 freeaddrinfo(server_infos); | |
| 81 | |
| 82 if (free_server_info == NULL) | |
| 83 { | |
| 84 perror("No free server"); | |
| 85 return -1; | |
| 86 } | |
| 87 | |
| 88 // TCP listen | |
| 89 if(stream) | |
| 90 { | |
| 91 if (listen(sock_fd, backlog) != 0) | |
| 92 { | |
| 93 perror("listen"); | |
| 94 return -1; | |
| 95 } | |
| 96 } | |
| 97 | |
| 98 return sock_fd; | |
| 99 } | |
| 100 |